Use razor language to write the-razorengine group "turn--very good, can use it instead of nvelocity"

Source: Internet
Author: User

Razorengine

Official web site: http://razorengine.codeplex.com

Before I found Razorengine, I had thought of other options, such as T4 and V8 engine download jquery.template, but T4 if you want to be independent of MSBuild or Visual Studio is a bit troublesome, and V8 engine I don't want to be in class. Library in the case of a bunch of JS files, and then think of Razor, because the Razor of the relationship is written in System.Web.Razor, although namespace called system.web, but there is no download any system.web related components ( So I'm sure it can be used in a non-web environment, and in the study of how to use it, it was found that someone wrote it on the CodePlex last year, and I was too outdated.

For a System.Web.Razor reference, only download the basic three components

Note: It is interesting to know how to use System.Web.Razor to produce results (mostly CodeDom), I know there are four sets, brother this article [ASP. Mvc]razor] [pre-compile] [1]- Accelerate the first time to execute the response speed introduction of the two extension and this article of the Razorengine and ASP. 3 use of the System.Web.WebPages.Razor, except System.Web.WebPages.Razor are open source can be downloaded code to observe.

The following example shows how to produce results (a bit tired, or better than others) if you only use System.Web.Razor.dll alone.

namespacerezorcodedomsample{Internal classProgram {Private Static voidMain (string[] args) {            //a simple paradigm            stringTemplate =@"@{var name= "" would "";} Hello @name !"; varinput =NewSystem.IO.StringReader (template); //the templateengine of producing razor            varHost =NewRazorenginehost (Newcsharprazorcodelanguage ()); Host. Defaultbaseclass="rezorcodedomsample.mytemplate"; Host. DefaultNamespace="Rezorcodedomsample"; Host. Defaultclassname="Mytemplateresult"; varEngine =NewRazortemplateengine (host); //the CodeDom that yielded the results            varCode =engine.            Generatecode (input); varCodeType = code. generatedcode.namespaces[0]. types[0]; varCodeprovider =NewCSharpCodeProvider (); //to get the CodeDom out of the file.//codegeneratoroptions options = new CodeGeneratorOptions (); //options.            Blanklinesbetweenmembers = true; //System.IO.StringWriter sw = new System.IO.StringWriter (); //Codeprovider.generatecodefromcompileunit (code.            Generatedcode, SW, Options); //file.writealltext ("C:\\text.cs", SW.            ToString ()); //Edit CodeDom            varOptions =NewCompilerParameters () {generateinmemory=true, GenerateExecutable=false,            }; Options. Referencedassemblies.add (typeof(program).            Assembly.location); varAsselby =codeprovider.compileassemblyfromdom (options, code.            Generatedcode); //Execute template.            varType = Asselby.CompiledAssembly.GetType ("Rezorcodedomsample.mytemplateresult"); varINS = Activator.CreateInstance (type) asMyTemplate; Ins.            Execute (); Console.Write (Ins.        Reault); }    }    //without base, it would be a bad idea.     Public classMyTemplate {PrivateStringBuilder SB =NewStringBuilder ();  Public Virtual voidExecute () {} Public voidWrite (Objectvalue) {sb.        Append (value); }         Public voidWriteliteral (Objectvalue) {sb.        Append (value); }         Public stringReault {Get{returnsb. ToString (); }        }    }}

Examples of use (partial direct use of the official network) general usage
string " Hello @Model. name! Welcome to razor! " ; string New "  World " " Sample ");

The last of the parameters is the option, but it is recommended that the value is given to the cache, and if so, the next time you use the same name, it will be fast, and it will be related to the include, Although Razorengine cannot be used with randeraction or randerpartial but is provided with an include can be loaded, also use this name as the key word.

Using the. cshtml file

As long as the file name is. cshtml, even if it is not in the ASP. cshtml in the same way (but without the setup in the Web. config, so some features come out), Of course, the file name does not have to be. cshtml, but there is no better IDE support.

Just write the law to change because ASP. NET MVC The BaseType of 3 is System.Web.Mvc.WebViewPage, and Razorengine's BaseType is RazorEngine.Templating.TemplateBase, except for the model of the other HTML , URLs, Ajax and so on are not, but C # 's language is supported.

string result = Razor.parse (File.readalltext ("test.cshtml"new  True"Wade" });

Advanced usage template's include

Razorengine does not support randeraction or randerpartial, but he has provided an include method to load the compile (or parse) past, the following are examples of use:

string " Hello @Model. Name " ; string " This is my sample template, @Include (\ "template1\", Model) "  "Template1"); string New " Wade " });
Embedded method

If there is a single range of methods that you can use to embed methods, here are the examples:

string @" @helper MyMethod (string name) {  Hello @name} @MyMethod (Model.name)! Welcome to razor! " ; string New "  World " });

BaseType

Each of these, eventually using System.Web.Razor.RazorTemplateEngine as class, and inheriting BaseType, so BaseType decided on the use of the function, if still unclear with the first example:

@" @{var name= "" would "";}  Hello @name ! ";

These are the things that are going to change into this.

//same as the Test.cs file that was produced after the first case was removed.namespacerezorcodedomsample{ Public classMyTemplateRsult:RezorCodeDomSample.MyTemplate { PublicMytemplatersult () {} Public Override voidExecute () {varName ="would"; Writeliteral ("Hello");            Write (name); Writeliteral ("!! \ r \ n"); }    }}

Does it have a clearer basetype function?

So if you want all of the features that can be used, you can continue to RazorEngine.Templating.TemplateBase, write the expansion function in the sub-category, and then register the sub-category, the following are examples of use:

 Public Abstract classMycustomtemplatebase<t>: templatebase<t>{   Public stringtoUpperCase (stringname) {    returnname.  toUpperCase (); }}//Registration of sub-categoryRazor.settemplatebase (typeof(mycustomtemplatebase<>));stringTemplate ="My name in UPPER case is: @ToUpperCase (model.name)";stringresult = Razor.parse (template,New{Name ="Matt"});

Loading components and naming spaces

Razorengine Register the CodeDom uses the AppDomain.CurrentDomain.GetAssemblies () method, so as long as in the case of the group, can be used in the scope of the test, but also to increase the convenience of writing, You can increase the name space by using the following example:

 
RAZOR.DEFAULTTEMPLATESERVICE.NAMESPACES.ADD ("system.xml"); string @" @{     var xml = new XmlDocument ();     Xml. LOADXML (Model);     Write (XML. INNERXML);} " ; string result = razor.parse<string"<Test>test</Test> ");

Setting files

Like ASP. NET MVC 31, name space or basetype, etc. can be written in the setup file, please refer to the Examiner network

Increase Zone

<?xml version="1.0" encoding="UTF-8" ?>< configuration>    <configSections>        <section name="razorengine" Type="RazorEngine.Configuration.RazorEngineConfigurationSection, razorengine" requirepermission="false" />    </configsections></configuration >

Add settings

<razorengine activator="RazorEngineSamples.Activators.MySampleActivator, Razorenginesamples"Factory="RazorEngine.Web.WebCompilerServiceFactory, Razorengine.web"> <namespaces> <addnamespace="System.Linq"/> </namespaces> <templateservicesdefault="Mycustomtemplateservice"> <add name="MyCustomTemplateService1"Language="CSharp"/> <add name="MyCustomTemplateService2"Templatebase="Mytemplatebase"/> </templateServices></razorEngine>

Templateservice can use different settings for some of these examples:

var service = razor.services["mycustomtemplateservice"]; string result = Service. Parse ("Hello @Model. Name"new"World" });

Original address: Http://www.dotblogs.com.tw/wadehuang36/archive/2011/08/07/razor-template-engine.aspx

Use razor language to write the-razorengine group "turn--very good, can use it instead of nvelocity"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.