是否可以在 asp.net 之外使用 Razor View Engine [英] Is it possible to use Razor View Engine outside asp.net

查看:24
本文介绍了是否可以在 asp.net 之外使用 Razor View Engine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我查看 Razor 视图引擎,我会看到一个非常漂亮和简洁的语法,它与生成 html 没有特别的联系.所以我想知道,在正常"的 .net 环境中使用 asp.net 外部的引擎有多容易,例如生成文本、代码......

欢迎提供任何指针、示例、评论或解释.

解决方案

这里有两个问题:

  1. 是的,您可以在 ASP.NET 应用程序域的上下文之外运行 Razor View Engine,如 Andrew 的博客中所述:http://vibrantcode.com/blog/2010/11/16/hosting-razor-outside-of-aspnet-revised-for-mvc3-rc.html
  2. 然而,Razor 仍然主要专注于生成类似 xml 的标记(例如 HTML),因为 Razor 解析器使用 的存在来确定代码和标记之间的转换.您可能可以使用它来生成任何文本,但当您的输出与 Razor 对您的意图的假设不符时,您可能会遇到问题.

例如,虽然这是有效的 Razor 代码(因为

标签):

@if(printHello) {<div>你好!</div>}

以下代码段无效(因为 Hello! 仍被视为代码):

@if(printHello) {你好!}

然而,有一个特殊的 标签可用于强制多行块的转换( 标签将不会被渲染):

@if(printHello) {<文字>你好!另一行}

还有一种更短的语法可以使用 @::

强制单行转换

@if(printHello) {@:你好!}

If I look at the Razor View Engine, then I see a very nice and concise syntax that is not particularly tied to generating html. So I wonder, how easy would it be to use the engine outside asp.net in a "normal" .net environment for example to generate text, code,...

Any pointer, example, comment or explanation is welcome.

解决方案

There are two issues here:

  1. Yes, you can run the Razor View Engine outside of the context of an ASP.NET app domain, as explained in Andrew's blog: http://vibrantcode.com/blog/2010/11/16/hosting-razor-outside-of-aspnet-revised-for-mvc3-rc.html
  2. However, Razor is still primarily focused on generating xml-like markup (e.g. HTML) in the sense that the Razor parser uses the presence of <tags> to determine the transition between code and markup. You can probably use it to generate any text but you might run into issues when your output doesn't match Razor's assumptions about what your intentions are.

So for example while this is valid Razor code (because of the <div> tag):

@if(printHello) {
   <div>Hello!</div>
}

The following snippet is invalid (because the Hello! is still being treated as code):

@if(printHello) {
   Hello!
}

However there's a special <text> tag that can be used to force a transition for multi-line blocks (the <text> tag will not be rendered):

@if(printHello) {
   <text>Hello!
   Another line</text>
}

There is also a shorter syntax to force a single line to transition using @::

@if(printHello) {
   @:Hello!
}

这篇关于是否可以在 asp.net 之外使用 Razor View Engine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆