在非MVC中使用Razor模板引擎

模板引擎介绍

Razor、Nvelocity、Vtemplate,Razor一般在MVC项目中使用,这里介绍在非MVC项目中的用法。

如何在非MVC中使用Razor模板引擎

借助于开源的RazorEngine,我们可以在非asp.net mvc项目中使用Razor引擎,甚至在控制台、WinForm项目中都可以使用Razor(自己开发代码生成器)

如何使用Razor

环境搭建:

1,添加引用RazorEngine.dll

2,创建cshtml

新建一个html,改名为cshtml。注意:通过 添加--html页再改成cshtml的方式打开是么有自动提示的,必须关掉该文件重新打开。推荐使用,添加--新建项--html页在这里直接改成cshtml创建cshtml文件,直接可用自动提示。

image

 

 

 

 

 

 

 

 

开始使用:

1,在cshtml中使用Razor语法

Razor中@后面跟表达式表示在这个位置输出表达式的值,模板中Model为传递给模板的对象。

@{}中为C#代码,C#代码还可以和html代码混排

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title></title>

</head>

<body>

    

    <ul>

    @{

        for (int i = 0; i < 10; i++)

        {

            <li>
@
i</li>

        }   

     }

        </ul>

</body>

</html>

2,在一般处理程序中使用Razor:

Razor对象会使用Parse方法将读取到的cshtml解析为一个程序集,再生成html。

public void ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "text/html";

            string fullPath=context.Server.MapPath(@"~/Razordemo/Razor1.cshtml");//拿到cshtml文件路径

            string cshtml=File.ReadAllText(fullPath);//得到文件内容

            string html = Razor.Parse(cshtml);//解析cshtml文件解析得到html

            context.Response.Write(html);

        }

3,如何在cshtml文件读取对象的值

Razor.Parse()方法的另一个重载就是传进一个Model对象,在cshtml文件中通过Model就可以点出来对象的属性。

在一般处理程序中解析:

            Dog dog = new Dog();

            dog.Id = 100;

            dog.Height = 120;

            string html = Razor.Parse(cshtml, dog);

            context.Response.Write(html);

在cshtml中读取对象属性:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title></title>

</head>

<body>



    <h1>狗狗信息:</h1>

    <h1>Id:@Model.Id</h1>

    <h1>身高:@Model.Height</h1>

    

</body>

</html>

你可能感兴趣的:(模板引擎)