码迷,mamicode.com
首页 > Web开发 > 详细

在非MVC中使用Razor模板引擎

时间:2015-06-07 17:03:24      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

模板引擎介绍

Razor、Nvelocity、Vtemplate,因为Razor在VS中有自动提示,使用方便有效率。

在非MVC中使用Razor模板引擎

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

如何使用Razor

环境搭建:

1,添加引用RazorEngine.dll

2,创建cshtml

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

具体用法:

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>

在非MVC中使用Razor模板引擎

标签:

原文地址:http://www.cnblogs.com/sean100/p/4558540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!