質問

I want to use RazorEngine to generate some html files. It's easy to generate strings first, then write them to files. But if the generated strings are too large, that will cause memory issues.

So I wonder is there a non-cached way to use RazorEngine, like using StreamWriter as its output rather than a string.

I google this for a while, but with no luck.
I think use a custom base template should be the right way, but the documents are so few(even out of date) on the offcial homepage of RazorEngine.

Any hint will be helpful!

役に立ちましたか?

解決

OK. I figured it out.

Create a class that inherits TemplateBase<T>, and take a TextWrite parameter in the constructor.

public class TextWriterTemplate<T> : TemplateBase<T>
{
    private readonly TextWriter _tw;

    public TextWriterTemplate(TextWriter tw)
    {
        _tw = tw;
    }

    // override Write and WriteLiteral methods, write text using the TextWriter.
    public override void Write(object value)
    {
        _tw.Write(value);
    }

    public override void WriteLiteral(string literal)
    {
        _tw.Write(literal);
    }
}

Then use the template as this:

private static void Main(string[] args)
{
    using (var sw = new StreamWriter(@"output.txt"))
    {
        var config = new FluentTemplateServiceConfiguration(c =>
            c.WithBaseTemplateType(typeof(TextWriterTemplate<>))
                .ActivateUsing(context => (ITemplate)Activator.CreateInstance(context.TemplateType, sw))
            );
        using (var service = new TemplateService(config))
        {
            service.Parse("Hello @Model.Name", new {Name = "Waku"}, null, null);
        }
    }
}

The content of output.txt should be Hello WAKU.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top