Detailed description of static pages (RazorEngine) and mvcrazorengine generated by ASP. net mvc parsing templates

Source: Internet
Author: User
Tags field table

Detailed description of static pages (RazorEngine) and mvcrazorengine generated by ASP. net mvc parsing templates

Brief Introduction

Razor is a newly added technology in ASP. net mvc 3 and serves as a new alternative to the ASPX engine. In earlier versions of MVC, The ASPX template engine is used by default. Razor is indeed good in syntax and very convenient to use. NET Framework is widely used in ASP.. net mvc project.

We often use static pages in many project development projects. There are many static pages. The most common method is to replace tags like many php cms methods (for example: CMS, EcShop, and so on), and many others are pseudo-static. We will not explain them too much, but we can simply rewrite the routing or Url. Razor provides us with a more convenient method for parsing templates. Everything is both technical and convenient, however, there are some technical requirements for template makers, or more considerations for developing a set of template creation functions. We no longer want to explore these issues. We pay more attention to which technology is easier, more convenient, and better able to meet the needs of our projects.

How to Use RazorEngine

Today, we will briefly introduce how to use RazorEngine to parse templates to generate static pages. RazorEngine is a template engine encapsulated based on Microsoft's Razor and can be used independently. That is to say, the Razor template function is retained, but Razor is isolated from Asp.net MVC and can be used in other application environments. Project address: RazorEngine_jb51.rar

First we go to codeplex to get up and down two dll http://razorengine.codeplex.com needed

I have seen a lot of basic usage of RazorEngine on the internet, and I have explained it in detail. The running principle of RazorEngine is clear and we will not repeat it here. This article is intended for many new students who prefer "take things" and can understand the basic usage principles. However, it is not clear how to apply it to projects, we will only talk about how to use it in projects.

This article is divided into two parts: the first part, basic single data model template parsing; the second part, interface-oriented multi-data model template Parsing

Part 1 Basic Analysis of Single data model templates

1. Create an MVC project and add the above two DLL references. Then we create a simple article class.

Public class Articles {// <summary> // article ID /// </summary> public int Id {get; set ;} /// <summary> /// article Title /// </summary> public string Title {get; set ;} /// <summary> /// article Content /// </summary> public string Content {get; set ;} /// <summary> /// Author /// </summary> public string Author {get; set ;} /// <summary> /// release time /// </summary> public DateTime CreateDate {get; set ;}}

2. Create a Razor Html template.

<! DOCTYPE html> 

Note: Model is our article entity class. In the attempt page of MVC, we generally pass this entity class in the Controller and then @ model Models on the view page. articles receives this object class and then uses "@ Model. the output content is the same in the Razor template, but the @ model Models is not required. and other syntaxes follow. the cshtml attempt is the same on the page. This is redundant because it is not Razor because it is written differently.

3. Write a method to obtain the Html code of the template page.

/// <Summary> /// obtain the Html code of the page /// </summary> /// <param name = "url"> template page path </param>/ // <param name = "encoding"> page encoding </param> // <returns> </returns> public string GetHtml (string url, system. text. encoding encoding) {byte [] buf = new WebClient (). downloadData (url); if (encoding! = Null) return encoding. getString (buf); string html = System. text. encoding. UTF8.GetString (buf); encoding = GetEncoding (html); if (encoding = null | encoding = System. text. encoding. UTF8) return html; return encoding. getString (buf );} /// <summary> // obtain the page encoding // </summary> /// <param name = "html"> Html source code </param> /// <returns> </returns> public System. text. encoding GetEncoding (string html) {string Pattern = @"(? I) \ bcharset = (? <Charset> [-a-zA-Z_0-9] +) "; string charset = Regex. match (html, pattern ). groups ["charset"]. value; try {return System. text. encoding. getEncoding (charset);} catch (ArgumentException) {return null ;}}

4. Write a method to generate Html static pages.

/// <Summary> /// create a static file /// </summary> /// <param name = "result"> Html code </param> /// <param name = "createpath"> generated path </param> // <returns> </returns> public bool CreateFileHtmlByTemp (string result, string createpath) {if (! String. isNullOrEmpty (result) {if (string. isNullOrEmpty (createpath) {createpath = "/default.html";} string filepath = createpath. substring (createpath. lastIndexOf (@ "\"); createpath = createpath. substring (0, createpath. lastIndexOf (@ "\"); if (! Directory. exists (createpath) {Directory. createDirectory (createpath);} createpath = createpath + filepath; try {FileStream fs2 = new FileStream (createpath, FileMode. create); StreamWriter sw = new StreamWriter (fs2, new System. text. UTF8Encoding (false); // remove the BOM sw from the UTF-8. write (result); sw. close (); fs2.Close (); fs2.Dispose (); return true ;}catch {return false ;}} return false ;}

5. Let's write a method to call the static template and pass the data model object class to create an Html static page.

/// <Summary> // parse the template to generate a static page // </summary> /// <param name = "temppath"> template address </param> // /<param name = "path"> static page address </param> // <param name = "t"> Data Model </param> // <returns> </returns> public bool CreateStaticPage (string temppath, string path, RazorEngineTemplates. models. articles t) {try {// obtain the template Html string TemplateContent = GetHtml (temppath, System. text. encoding. UTF8); // initialization result string result = string. empty; // parse the template to generate the static page Html code result = Razor. parse (TemplateContent, t); // create a static file return CreateFileHtmlByTemp (result, path);} catch (Exception e) {throw e ;}}

Well, it's easy.

Here is just a very simple application. There is no data read or list, and there is only one article data model. The next section will introduce multi-model template parsing, because it is a multi-model, reflection is used instead of passing a specific model entity class when generating a static page. If you are unfamiliar with reflection, you can take a look at it in advance, you can also directly view the reflection code in the next part.

Part 2 interface-oriented multi-data model template Analysis

In this section, we will introduce the use of interfaces to parse templates, including list and other models, Spring injection and reflection, and interfaces. If you are unfamiliar with this, you can search for them or leave a comment.

In the preceding example, we create two new class libraries. One is the Domain that stores the data model, and the other is the Service that stores interfaces and implementation classes. Then we add references between them.

I. Create several test classes under Domain

Articles-Article Testing

Company-Company testing

Column-Column Testing

TemplateView-model parsing class (is this relatively retarded? I have not studied how to reflect multiple models in depth, so I added such a public class. No corresponding data tables are used only as middleware when parsing templates)

Public class Articles {// <summary> // article ID /// </summary> public int Id {get; set ;} /// <summary> /// article Title /// </summary> public string Title {get; set ;} /// <summary> /// article Content /// </summary> public string Content {get; set ;} /// <summary> /// Author /// </summary> public string Author {get; set ;} /// <summary> /// release time /// </summary> public DateTime CreateDate {get; set ;}} public class Company {// <summary> /// Company Id /// </summary> public int Id {get; set ;} /// <summary> /// company name // </summary> public string CompanyName {get; set ;} /// <summary> // company phone number // </summary> public string CompanyTel {get; set ;} /// <summary> /// contact /// </summary> public string ContectUser {get; set ;} /// <summary> /// creation time /// </summary> public DateTime CreateDate {get; set ;}} public class Column {// <summary> /// topic ID /// </summary> public int Id {get; set ;} /// <summary> /// topic name /// </summary> public string Title {get; set ;} /// <summary >/// document list /// </summary> public virtual ICollection <Articles> Articles {get; set ;}} public class TemplateView {// <summary> /// ID // </summary> public int Id {get; set ;} /// <summary> /// Title /// </summary> public string Title {get; set ;} /// <summary> /// Content /// </summary> public string Content {get; set ;} /// <summary> /// Author /// </summary> public string Author {get; set ;} /// <summary> /// time /// </summary> public DateTime CreateDate {get; set ;} /// <summary> /// company name // </summary> public string CompanyName {get; set ;} /// <summary> // company phone number // </summary> public string CompanyTel {get; set ;} /// <summary> /// contact /// </summary> public string ContectUser {get; set ;} /// <summary >/// document list /// </summary> public virtual ICollection <Articles> Articles {get; set ;}}

2. Create a basic operation interface and its implementation class under the Service (there are many methods in it, such: it is not necessary to write the Html code of the page, get the code of the page, and create a static file. This interface can be written to a public class library, because these methods are used here, I did not add a public class library and wrote it directly here)

/// <Summary> /// basic operation interface /// </summary> /// <typeparam name = "T"> </typeparam> public interface IRepository <T> where T: class {// <summary> /// parse the template to generate a static page // </summary> /// <param name = "temppath"> template address </param> /// <param name = "path"> static page address </param> /// <param name = "t"> Data Model </param> /// <returns> </returns> bool CreateStaticPage (string temppath, string path, T t); // <summary> // obtain the Html code of the page. /// </sum Mary> /// <param name = "url"> template page path </param> /// <param name = "encoding"> page Code </param> /// <returns> </returns> string GetHtml (string url, system. text. encoding encoding ); /// <summary> // obtain the page encoding // </summary> /// <param name = "html"> Html source code </param> /// <returns> </returns> System. text. encoding GetEncoding (string html ); /// <summary> /// create a static file /// </summary> /// <param name = "result"> Html code </param> /// <Param name = "createpath"> generated path </param> // <returns> </returns> bool CreateFileHtmlByTemp (string result, string createpath );} /// <summary> /// basic interface implementation class /// </summary> /// <typeparam name = "T"> </typeparam> public abstract class RepositoryBase <t>: IRepository <T> where T: class {// <summary> /// parse the template to generate a static page // </summary> /// <param name = "temppath"> template address </param> /// <param name = "path"> static page address </param> /// <Param name = "t"> Data Model </param> // <returns> </returns> public bool CreateStaticPage (string temppath, string path, T t) {try {// instantiate the Model var Entity = new Domain. templateView (); // obtain the template Html string TemplateContent = GetHtml (temppath, System. text. encoding. UTF8); // initialization result string result = ""; // reflection value: Type typeT = t. getType (); Type typeEn = Entity. getType (); System. reflection. propertyInfo [] propertyinfosT = t YpeT. GetProperties (); foreach (System. Reflection. PropertyInfo propertyinfoT in propertyinfosT) {System. Reflection. PropertyInfo propertyinfoEn = typeEn. GetProperty (propertyinfoT. Name); if (propertyinfoEn! = Null & propertyinfoT. GetValue (t, null )! = Null) {propertyinfoEn. setValue (Entity, propertyinfoT. getValue (t, null), null );}} // In many cases, we have not created a complex primary/foreign key relationship. For example, if an article under a topic adds a field of the topic ID in the article table, // the association is not created. when we directly retrieve a column, we cannot obtain the article list. // There are many custom models and fields. For example, the content of the article may not be a table with the article, but a separate big data field table. in this case, our // TemplateView. content needs to obtain the Content of this article in another data model. In this case, we can re-assign a value to it here. // For example, the input model is the article // if (t is Domain. articles) // {// Entity. content = query the Content of this article in the big data field table; //} result = Razor. parse (TemplateContent, Entity); return CreateFileHtmlByTemp (result, path);} catch (Exception e) {throw e ;}} /// <summary> /// obtain the Html code of the page /// </summary> /// <param name = "url"> template page path </param>/ // <param name = "encoding"> page encoding </param> // <returns> </returns> public string GetHtml (string url, system. text. encoding encoding) {byte [] buf = new WebClient (). downloadData (url); if (encoding! = Null) return encoding. getString (buf); string html = System. text. encoding. UTF8.GetString (buf); encoding = GetEncoding (html); if (encoding = null | encoding = System. text. encoding. UTF8) return html; return encoding. getString (buf );} /// <summary> // obtain the page encoding // </summary> /// <param name = "html"> Html source code </param> /// <returns> </returns> public System. text. encoding GetEncoding (string html) {string Pattern = @"(? I) \ bcharset = (? <Charset> [-a-zA-Z_0-9] +) "; string charset = Regex. match (html, pattern ). groups ["charset"]. value; try {return System. text. encoding. getEncoding (charset);} catch (ArgumentException) {return null ;}} /// <summary> /// create a static file /// </summary> /// <param name = "result"> Html code </param> /// <param name = "createpath"> generated path </param> // <returns> </returns> public bool CreateFileHtmlByTemp (string result, string c Reatepath) {if (! String. isNullOrEmpty (result) {if (string. isNullOrEmpty (createpath) {createpath = "/default.html";} string filepath = createpath. substring (createpath. lastIndexOf (@ "\"); createpath = createpath. substring (0, createpath. lastIndexOf (@ "\"); if (! Directory. exists (createpath) {Directory. createDirectory (createpath);} createpath = createpath + filepath; try {FileStream fs2 = new FileStream (createpath, FileMode. create); StreamWriter sw = new StreamWriter (fs2, new System. text. UTF8Encoding (false); // remove the BOM sw from the UTF-8. write (result); sw. close (); fs2.Close (); fs2.Dispose (); return true ;}catch {return false ;}}

3. We create the document management, company management, and topic management interfaces and implementation classes respectively, and they all integrate basic operations.

/// <Summary> /// document management /// </summary> public interface IArticleManage: IRepository <Domain. articles >{} public class ArticleManage: RepositoryBase <Domain. articles>, IArticleManage {}/// <summary> // company management /// </summary> public interface ICompanyManage: IRepository <Domain. company >{} public class CompanyManage: RepositoryBase <Domain. company>, ICompanyManage {}// topic management public interface IColumnManage: IRepository <Domain. column >{} public class ColumnManage: RepositoryBase <Domain. column>, IColumnManage {}

Iv. Xml injection

<? Xml version = "1.0" encoding = "UTF-8"?> <Objects xmlns = "http://www.springframework.net"> <description> Spring injection Service, the container points to the encapsulated interface </description> <object id = "Service. articleManage "type =" Service. articleManage, Service "singleton =" false "> </object> <object id =" Service. columnManage "type =" Service. columnManage, Service "singleton =" false "> </object> <object id =" Service. companyManage "type =" Service. companyManage, Service "singleton =" false "> </object> </objects>

5. Initialize an article class and a company class respectively. (no data table is managed. I will not initialize the topic model without an article list. For how to output the list, refer to the topic template below)

Public class HomeController: Controller {// <summary> // declare the Injection Interface /// </summary> public IArticleManage ArticleManage = Spring. context. support. contextRegistry. getContext (). getObject ("Service. articleManage ") as IArticleManage; public ICompanyManage CompanyManage = Spring. context. support. contextRegistry. getContext (). getObject ("Service. companyManage ") as ICompanyManage; public IColumnManage ColumnManage = Spring. context. support. contextRegistry. getContext (). getObject ("Service. columnManage ") as IColumnManage; public ActionResult Index () {// Initialize an article Data Model var entityArticle = new Domain. articles () {Id = 1, Title = "here is the article Title", Content = "<span style = \" color: red; \ "> here is the content of the article </span>", Author = "zhangsan", CreateDate = DateTime. now}; // initialize a company Data Model var entityCompany = new Domain. company () {Id = 1, CompanyName = "Company name", CompanyTel = "Company phone", ContectUser = "Zhang San", CreateDate = DateTime. now}; // call the method to generate the static page ArticleManage. createStaticPage (Server. mapPath ("/Templates/Temp_article.html"), Server. mapPath ("/Pages/news/" + DateTime. now. toString ("yyyyMMddHHmmss") + "1.html"), entityArticle); CompanyManage. createStaticPage (Server. mapPath ("/Templates/Temp_company.html"), Server. mapPath ("/Pages/news/" + DateTime. now. toString ("yyyyMMddHHmmss") + "2.html"), entityCompany); return View ();} public ActionResult About () {ViewBag. message = "Your application description page. "; return View ();} public ActionResult Contact () {ViewBag. message = "Your contact page. "; return View ();}}

6. This is a simple document template, company template, and topic template for testing.

<! DOCTYPE html> 
<! DOCTYPE html>  
<! DOCTYPE html> 

Let's run it. We're done ~~~

 

 

How to sort? How to get the first few items? How to format the date and time? How to paging?

This is Razor. You don't need to talk about it any more. To put it simply, if you didn't sort the data or retrieve the first few items before passing in the data, the operations in the template should follow. basically the same in cshtml

@foreach(var item in @Model.ListColumn){ <div >@if (@item.LinkUrl==null)  {    <ul>@foreach(var article in @item.COM_ARTICLE.Take(15).OrderByDescending(p=>p.UpDateDate)){<li>      <a href="@article.LinkUrl" rel="external nofollow" class="gd-a">        <div>@article.Title</div></a>      </li>} </ul>   }  else   {  }</div>}

It is still widely used, and the parsing code is very simple and efficient than tag replacement. If you have time to study more, you can write a template to replace the tag for your reference. Some people may say that I have to teach the front-end to create Razor syntax. We cannot comment on this statement. You still need to teach him how to use tags to replace tags, so it is not the subject of inquiry that is not complicated, it is not a major factor for front-end developers to easily create a template syntax. For example, we can make a convenient template. Users can click it to generate code or directly make it visualized, this may make our Programmers spend more energy, but once and for all, you still need to set a tag specification and syntax for the front-end developers, besides, the background Parsing is huge and complex.

 

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.