目录
The Super Simple View Engine
Standard variable substitution
Iterators
Conditionals
Implicit Conditionals
HTML Encoding
Partials
Master pages and sections
Anti-forgery token
Path expansion
SSVEModule.cs
Razor View Engine
安装
使用
RazorModule.cs
项目结构
首页 web前端 html教程 Nancy 学习-视图引擎 继续跨平台_html/css_WEB-ITnose

Nancy 学习-视图引擎 继续跨平台_html/css_WEB-ITnose

Jun 24, 2016 am 11:28 AM

前面一篇,讲解Nancy的基础,以及Nancy自宿主,现在开始学习视图引擎。

Nancy 目前支持两种 一个是SSVE 一个是Razor。下面我们一起学习。

The Super Simple View Engine

SSVE 全称就是 Super Simple View Engine ,翻译过来也就是 超级简单视图引擎

我们在Nancy 不需单独引用,因为它是默认内置的。该引擎处理任何sshtml,html或htm文件 。

模型可以是标准的类型,或ExpandoObject(或者实现 IDynamicMetaObjectProvider ,或者实现的IDictionary 以访问其属性)。

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!]

Syntax

@Model[.Parameters]
登录后复制

Example

Hello @Model.Name, your age is @Model.User.Age
登录后复制

Iterators

Enables you to iterate over models that are collection. Iterators cannot be nested

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!@EndEach
登录后复制

Conditionals

Parameters must be a boolean (see Implicit Conditionals below). Nesting of @If and @IfNot statements is not supported.

Syntax:

@If[Not].Parameters   [contents]@EndIf
登录后复制

Example

@IfNot.HasUsers   No users found!@EndIf
登录后复制

Implicit 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 the Parameters part can have a Has -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!@EndIf
登录后复制

The 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@EndEach
登录后复制

Partials

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>']@EndSection
登录后复制

Example

// master.sshtml<html><body>@Section['Content'];</body></html>// index.sshtml@Master['master.sshtml']@Section['Content']   This is content on the index page@EndSection
登录后复制

Anti-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

@AntiForgeryToken
登录后复制
登录后复制

Example

@AntiForgeryToken
登录后复制
登录后复制

Path 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 around value ) where attribute value starts with ~/ . For example, can be significantly shortened to .

下面来讲解一些常用的命令。

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
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 View Engine

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

其他语法与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<!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
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

如果你觉得本文对你有帮助,请点击“ 推荐 ”,谢谢。

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它们
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

&gt; gt;的目的是什么 元素? &gt; gt;的目的是什么 元素? Mar 21, 2025 pm 12:34 PM

本文讨论了HTML&lt; Progress&gt;元素,其目的,样式和与&lt; meter&gt;元素。主要重点是使用&lt; progress&gt;为了完成任务和LT;仪表&gt;对于stati

&lt; datalist&gt;的目的是什么。 元素? &lt; datalist&gt;的目的是什么。 元素? Mar 21, 2025 pm 12:33 PM

本文讨论了html&lt; datalist&gt;元素,通过提供自动完整建议,改善用户体验并减少错误来增强表格。Character计数:159

HTML5中跨浏览器兼容性的最佳实践是什么? HTML5中跨浏览器兼容性的最佳实践是什么? Mar 17, 2025 pm 12:20 PM

文章讨论了确保HTML5跨浏览器兼容性的最佳实践,重点是特征检测,进行性增强和测试方法。

&lt; meter&gt;的目的是什么。 元素? &lt; meter&gt;的目的是什么。 元素? Mar 21, 2025 pm 12:35 PM

本文讨论了HTML&lt; meter&gt;元素,用于在一个范围内显示标量或分数值及其在Web开发中的常见应用。它区分了&lt; meter&gt;从&lt; progress&gt;和前

如何使用HTML5表单验证属性来验证用户输入? 如何使用HTML5表单验证属性来验证用户输入? Mar 17, 2025 pm 12:27 PM

本文讨论了使用HTML5表单验证属性,例如必需的,图案,最小,最大和长度限制,以直接在浏览器中验证用户输入。

视口元标签是什么?为什么对响应式设计很重要? 视口元标签是什么?为什么对响应式设计很重要? Mar 20, 2025 pm 05:56 PM

本文讨论了视口元标签,这对于移动设备上的响应式Web设计至关重要。它解释了如何正确使用确保最佳的内容缩放和用户交互,而滥用可能会导致设计和可访问性问题。

&lt; iframe&gt;的目的是什么。 标签?使用时的安全考虑是什么? &lt; iframe&gt;的目的是什么。 标签?使用时的安全考虑是什么? Mar 20, 2025 pm 06:05 PM

本文讨论了&lt; iframe&gt;将外部内容嵌入网页,其常见用途,安全风险以及诸如对象标签和API等替代方案的目的。

Gitee Pages静态网站部署失败:单个文件404错误如何排查和解决? Gitee Pages静态网站部署失败:单个文件404错误如何排查和解决? Apr 04, 2025 pm 11:54 PM

GiteePages静态网站部署失败:404错误排查与解决在使用Gitee...

See all articles