前面一篇,講解Nancy的基礎,以及Nancy自宿主,如今開始學習視圖引擎。html
Nancy 目前支持兩種 一個是SSVE 一個是Razor。下面咱們一塊兒學習。linux
SSVE 全稱就是 Super Simple View Engine ,翻譯過來也就是 超級簡單視圖引擎。git
咱們在Nancy 不需單獨引用,由於它是默認內置的。該引擎處理任何sshtml,html或htm文件。github
模型能夠是標準的類型,或ExpandoObject(或者實現 IDynamicMetaObjectProvider ,或者實現的IDictionary<string,object> 以訪問其屬性)。web
SSVE是一個基於正則表達式的視圖引擎,沒有「執行代碼」,因此你不能指定本身的代碼來執行。內置的語法/命令,你可使用以下所示。正則表達式
Standard variable substitution
Replaces with the string representation of the parameter, or the model itself if a parameter is not specified. If the substitution can not be performed, for instance if you specify an invalid model property, it will be substituted with
[Err!]
appSyntaxssh
@Model[.Parameters]Exampleide
Hello @Model.Name, your age is @Model.User.AgeIterators
Enables you to iterate over models that are collection. Iterators cannot be nestedpost
Syntax
@Each[.Parameters] [@Current[.Parameters]] @EndEach
@Each
will implicitly be associated with the model and for each iteration the@Current
will represent the current item in the collection.@Current
can be used multiple times in the iterator block, and is accessed in the same way as@Model
.Example
@Each.Users Hello @Current.Name! @EndEachConditionals
Parameters must be a boolean (see Implicit Conditionals below). Nesting of @If and @IfNot statements is not supported.
Syntax:
@If[Not].Parameters [contents] @EndIfExample
@IfNot.HasUsers No users found! @EndIfImplicit Conditionals
If the model has property that implements
ICollection
then you can use an implicit conditional. The implicit conditional syntax is the same as a normal conditional, but theParameters
part can have aHas
-prefix. The conditional will be true if the collection contains items, and false if it does not or if it is null.Syntax
Has[CollectionPropertyName]Example
@If.HasUsers Users found! @EndIfThe above example will expand to "Users found!" if the model has a collection called
Users
and it contains items; if the collection is empty then the text would not be displayed.HTML Encoding
Both the
@Model
and@Current keywords
(with or without parameters) can have an optional!
operator, after the@
, to HTML encode the output.Syntax
@!Model[.Parameter] @!Current[.Parameter]Example
@!Model.Test @Each @!Current.Test @EndEachPartials
Renders a partial view. A property of the current model can be specified to be used as the partial view's model, or it may be omitted to use the current view's model instead. The file extension of the view is optional.
Syntax
@Partial['<view name>'[, Model.Property]]Example
// Renders the partial view with the same model as the parent @Partial['subview.sshtml']; // Renders the partial view using the User as the model @Partial['subview.sshtml', Model.User];Master pages and sections
You can put shared layout in a master page and declare content sections that will be populated by the views. It is possible to have nested master pages and you are not obligated to provide content for all of the content sections.
The master pages will have access to the
@Model
of the view and the file extension is optional when specifying the name of the master to use in your view.You can use the
@Section
tag multiple times and is used to both declare a content section, in a master page, and to define the content blocks of a view.Syntax
@Master['<name>'] @Section['<name>'] @EndSectionExample
// master.sshtml <html> <body> @Section['Content']; </body> </html> // index.sshtml @Master['master.sshtml'] @Section['Content'] This is content on the index page @EndSectionAnti-forgery token
Renders an anti-forgery token, on the page, in an hidden input to prevent cross-site request forgery attacks. The token will automatically be validated when a new request is posted to the server (assuming CSRF protection hasn’t been turned off).
Syntax
@AntiForgeryTokenExample
@AntiForgeryTokenPath expansion
Expands a relative paths to a fully qualified URL.
Syntax
@Path['<relative-path>']Example
@Path['~/relative/url/image.png']Starting from v1.2, SSVE performs automatic path expansion in all HTML attributes (more specifically, in all
name="value"
pairs, both with single and double quotes aroundvalue
) where attribute value starts with~/
. For example,<a href="@Path['~/relative/path']" ...>
can be significantly shortened to<a href="~/relative/path" ...>
.
下面來說解一些經常使用的命令。
1.Model
2.Each
3.If
4.Partials
5.Master pages and sections
首先建立一個項目。建議建立web空項目 。
我是直接使用上次的項目 http://www.cnblogs.com/linezero/p/5121887.html
先建立一個Module SSVEModule
而後添加Views文件夾 -》而後再在其下添加 SSVE文件夾 -》添加對應的View 頁。
這樣使項目更加清楚。
1.Model
Get["/model"] = r => { var model = "我是字符串"; return View["model", model]; };
在SSVE 文件夾下添加一個model.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body> @Model </body> </html>
而後咱們訪問頁面 訪問地址: http://localhost:9000/ssve/model
2.Each
Get["/each"] = r => { var arr = new int[] { 3, 6, 9, 12, 15, 12, 9, 6, 3 }; return View["each", arr]; };
each.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body> @Each <p>@Current</p> @EndEach </body> </html>
訪問地址: http://localhost:9000/ssve/each
3.If
Get["/if"] = r => { return View["if", new { HasModel = true }]; };
if.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body> @If.HasModel <p>我出現了</p> @EndIf @IfNot.HasModel <p>我沒辦法出現</p> @EndIf </body> </html>
訪問地址: http://localhost:9000/ssve/if
4.Partials
@Partial['header.html']
在SSVE 下添加header.html 而後在頁面添加這句便可。
5.Master pages and sections
master.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body> @Partial['header.html'] @Section['Content'] </body> </html>
使用 master
@Master['master.html'] @Section['Content'] <p>master partial content 結合</p> @Model @EndSection
SSVEModule.cs
using Nancy; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NancyDemo { public class SSVEModule : NancyModule { public SSVEModule():base("/ssve") { Get["/"] = r => { var os = System.Environment.OSVersion; return "Hello SSVE<br/> System:" + os.VersionString; }; Get["/model"] = r => { var model = "我是字符串"; return View["model", model]; }; Get["/each"] = r => { var arr = new int[] { 3, 6, 9, 12, 15, 12, 9, 6, 3 }; return View["each", arr]; }; Get["/if"] = r => { return View["if", new { HasModel = true }]; }; } } }
SSVE視圖引擎源碼:https://github.com/grumpydev/SuperSimpleViewEngine
Razor 相信你們都是很是熟悉,因此也就不在這裏過多作語法講解。
主要是講解在Nancy中使用Razor 視圖引擎。
Nancy 的Razor 是自定義實現的,因此與ASP.NET MVC 中的Razor 有所不一樣。
在Nancy中綁定模型是@Model 不是ASP.NET MVC @model
要在Nancy中使用Razor 須要安裝 Nancy.ViewEngines.Razor
Nuget:Install-Package Nancy.Viewengines.Razor
添加Razor之後,會默認在app.config 添加Razor相關配置。
建議你們新建一個空的web項目,這樣便於編寫視圖。
在視圖中聲明 關鍵字爲:@inherits
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
其餘語法與ASP.NET MVC Razor相同。
我仍是在原項目上進行添加。
先建立一個Module RazorModule
而後添加Views文件夾 -》而後再在其下添加 Razor文件夾 -》添加對應的View 頁。以 cshtml結尾的文件,也就是視圖文件。
1.Model
Get["/index"] = r => { var model = "我是 Razor 引擎"; return View["index",model]; };
index.cshtml
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic> <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body> @Model </body> </html>
訪問地址: http://localhost:9000/razor/index
2.each
Get["/each"] = r => { var arr = new int[] { 3, 6, 9, 12, 15, 12, 9, 6, 3 }; return View["each", arr]; };
雖然Module中的代碼與前面相同。但View 就不同了。
each.cshtml
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic> <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body> @foreach (var item in Model) { <p>@item</p> } </body> </html>
訪問地址: http://localhost:9000/razor/each
RazorModule.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Nancy; namespace NancyDemo { public class RazorModule:NancyModule { public RazorModule() :base("/razor") { Get["/"] = r => { var os = System.Environment.OSVersion; return "Hello Razor<br/> System:" + os.VersionString; }; Get["/index"] = r => { var model = "我是 Razor 引擎"; return View["index",model]; }; Get["/each"] = r => { var arr = new int[] { 3, 6, 9, 12, 15, 12, 9, 6, 3 }; return View["each", arr]; }; } } }
由於我使用的項目是控制檯程序,Views 文件夾下的文件必須都要在 屬性 選擇 始終複製 。
在linux上運行能夠參考上篇文章。
最後留個坑,下一篇:Nancy 學習-進階部分 繼續跨平臺。請你們多多支持。
參考連接:
https://github.com/NancyFx/Nancy/wiki/The-Super-Simple-View-Engine
若是你以爲本文對你有幫助,請點擊「推薦」,謝謝。