Nancy 学习-视图引擎 继续跨平台
前面一篇,讲解Nancy的基础,以及Nancy自宿主,现在开始学习视图引擎。
Nancy 目前支持两种 一个是SSVE 一个是Razor。下面我们一起学习。
The Super Simple View Engine
SSVE 全称就是 Super Simple View Engine ,翻译过来也就是 超级简单视图引擎。
我们在Nancy 不需单独引用,因为它是默认内置的。该引擎处理任何sshtml,html或htm文件。
模型可以是标准的类型,或ExpandoObject(或者实现 IDynamicMetaObjectProvider ,或者实现的IDictionary<string,object> 以访问其属性)。
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
@Eachwill implicitly be associated with the model and for each iteration the@Currentwill represent the current item in the collection.@Currentcan 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
ICollectionthen you can use an implicit conditional. The implicit conditional syntax is the same as a normal conditional, but theParameterspart 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!
@EndIf
The above example will expand to "Users found!" if the model has a collection called
Usersand it contains items; if the collection is empty then the text would not be displayed.HTML Encoding
Both the
@Modeland@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
@Modelof the view and the file extension is optional when specifying the name of the master to use in your view.You can use the
@Sectiontag 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 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[] { , , , , , , , , };
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[] { , , , , , , , , };
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<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[] { , , , , , , , , };
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[] { , , , , , , , , };
return View["each", arr];
};
}
}
}
项目结构

因为我使用的项目是控制台程序,Views 文件夹下的文件必须都要在 属性 选择 始终复制 。
在linux上运行可以参考上篇文章。
最后留个坑,下一篇:Nancy 学习-进阶部分 继续跨平台。请大家多多支持。
参考链接:
https://github.com/NancyFx/Nancy/wiki/The-Super-Simple-View-Engine
如果你觉得本文对你有帮助,请点击“推荐”,谢谢。
Nancy 学习-视图引擎 继续跨平台的更多相关文章
- Nancy 学习-进阶部分 继续跨平台
前面两篇,讲解Nancy的基础,及Nancy自宿主和视图引擎. 现在来学习一些进阶部分. Bootstrapper Bootstrapper 就相当于 asp.net 的Global.asax . 我 ...
- Nancy 学习-自宿主 继续跨平台
Nancy简介 Nancy是一个轻量级的独立的框架,下面是官网的一些介绍: Nancy 是一个轻量级用于构建基于 HTTP 的 Web 服务,基于 .NET 和 Mono 平台,框架的目标是保持尽可能 ...
- Nancy in .Net Core学习笔记 - 视图引擎
前文中我们介绍了Nancy中的路由,这一篇我们来介绍一下Nancy中的视图引擎. Nancy中如何返回一个视图(View) 在ASP.NET Mvc中,我们使用ViewResult类来返回一个视图.N ...
- MVC系列——MVC源码学习:打造自己的MVC框架(四:了解神奇的视图引擎)
前言:通过之前的三篇介绍,我们基本上完成了从请求发出到路由匹配.再到控制器的激活,再到Action的执行这些个过程.今天还是趁热打铁,将我们的View也来完善下,也让整个系列相对完整,博主不希望烂尾. ...
- ASP.Net MVC开发基础学习笔记:三、Razor视图引擎、控制器与路由机制学习
一.天降神器“剃须刀” — Razor视图引擎 1.1 千呼万唤始出来的MVC3.0 在MVC3.0版本的时候,微软终于引入了第二种模板引擎:Razor.在这之前,我们一直在使用WebForm时代沿留 ...
- ASP.Net MVC开发基础学习笔记(3):Razor视图引擎、控制器与路由机制学习
一.天降神器“剃须刀” — Razor视图引擎 1.1 千呼万唤始出来的MVC3.0 在MVC3.0版本的时候,微软终于引入了第二种模板引擎:Razor.在这之前,我们一直在使用WebForm时代沿留 ...
- Razor视图引擎 语法学习(一)
ASP.NET MVC是一种构建web应用程序的框架,它将一般的MVC(Model-View-Controller)模式应用于ASP.NET框架: ASP.NET约定优于配置:基本分为模型(对实体数据 ...
- MVC学习三:Razor视图引擎
1.Razor视图引擎,主要是把View的HTML代码编译到View视图类对象中
- ASP.NET MVC学习---(七)Razor视图引擎语法
之前体验过razor视图引擎@符号的威力了吧~ 连我这个初学者都能感觉到确实省时省力方便快捷 简直就是居家旅行*人*货必备之物啊(这里和谐两个字~) 那么现在就开始对razor的语法进一步介绍~ 1. ...
随机推荐
- 【吐血分享】SQL Server With As 递归获取层级关系数据
纯洁的一周又开始了,今天看到一则新闻,笑尿了,和袁友们一起娱乐下 最近两月在做基于Saas模式的人力资源管理产品,平常数据库设计我经常会遇到如下需求场景: 以前商城类网站在设计类型表的时候,设计成单表 ...
- 一天一小段js代码(no.4)
最近在看网上的前端笔试题,借鉴别人的自己来试一下: 题目: 写一段脚本,实现:当页面上任意一个链接被点击的时候,alert出这个链接在页面上的顺序号,如第一个链接则alert(1), 依次类推. 有一 ...
- WCF Data Service
WCF Data Service:http://www.cnblogs.com/shanyou/category/240225.html
- 使用Chef管理windows集群
但凡服务器上了一定规模(百台以上),普通的ssh登录管理的模式就越来越举步维艰.试想Linux发布了一个高危漏洞的补丁,你要把手下成百上千台机器都更新该补丁,如果没有一种自动化方式,那么至少要耗上大半 ...
- AWS系列之二 使用EC2
在本文中我们有三个任务. 第一:使用Amazon management console创建一个EC2实例. 第二:使用本地的命令行工具远程登陆到该EC2实例. 第三:在该EC2实例上创建一个web服务 ...
- Mybatis入门例子
Mybatis是轻量级的持久化框架,的确上手非常快. Mybatis大体上的思路就是由一个总的config文件配置全局的信息,比如mysql连接信息等.然后再mapper中指定查询的sql,以及参数和 ...
- hibernate学习笔记之一 hibernate简介
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架 hibernate可以自动生成SQL语句,自 ...
- Android 控件架构及View、ViewGroup的测量
附录:示例代码地址 控件在Android开发的过程中是必不可少的,无论是我们在使用系统控件还是自定义的控件.下面我们将讲解一下Android的控件架构,以及如何实现自定义控件. 1.Android控件 ...
- Python下划线与命名规范
Python下划线与命名规范 先看结论,节省只想知道答案你的宝贵时间: _xxx 不能用于from module import * 以单下划线开头的表示的是protected类型的变量.即保护类型只能 ...
- oracle11g AUD$维护
SYSTEM表空间使用率达到了85%,查出是用来记录审计记录的aud$表占用了很大的空间. 备份后truncate掉AUD$,问题临时解决.记得oracle11.2可以把aud$迁移到普通的表空 间. ...