Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

c# - Templating using new RazorEngine API

Some time ago rendering a template using RazorEngine was as easy as:

string s = RazorEngine.Razor.Parse()

However, for some reason, its authors changed their minds about the API and now the simplest way to render a template is:

var key = new RazorEngine.Templating.NameOnlyTemplateKey("EmailTemplate", RazorEngine.Templating.ResolveType.Global, null);
RazorEngine.Engine.Razor.AddTemplate(key, new RazorEngine.Templating.LoadedTemplateSource("Ala ma kota"));
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
RazorEngine.Engine.Razor.RunCompile(key, sw);
string s = sb.ToString();

(at least this is what I deduced from the new API. Old one is marked as deprecated.) Is there a way to use new API to render a template without caching, keys and other fancy stuff? All official examples simply doesn't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, after searching the code, I found some useful examples (https://github.com/Antaris/RazorEngine/blob/master/src/source/RazorEngine.Hosts.Console/Program.cs) and found out that if you include

using RazorEngine.Templating;

at the top of your class, you can use some extension methods (https://github.com/Antaris/RazorEngine/blob/master/src/source/RazorEngine.Core/Templating/RazorEngineServiceExtensions.cs) that will help you.

Painless template compilation :

Engine.Razor.Compile(templatePath, "templateNameInTheCache", modelType);

Template Parsing :

Engine.Razor.Run("templateNameInTheCache", modelType, model);

And now you can do both at the same time !

string myParsedTemplate = Engine.Razor.RunCompile(templatePath, "templateNameInTheCache", null, model)

Which is the equivalent of doing this

Engine.Razor.AddTemplate("templateNameInTheCache", TemplateLoader.GetTemplate(templatePath));
Engine.Razor.Compile("templateNameInTheCache", modelType);
string finallyThisIsMyParsedTemplate = Engine.Razor.Run("templateNameInTheCache", modelType);

Please note that I'm currently testing this, but it seems to work fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...