찾다
웹 프론트엔드HTML 튜토리얼Nancy 学习-视图引擎 继续跨平台_html/css_WEB-ITnose

前面一篇,讲解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으로 문의하세요.
HTML vs. CSS vs. JavaScript : 비교 개요HTML vs. CSS vs. JavaScript : 비교 개요Apr 16, 2025 am 12:04 AM

웹 개발에서 HTML, CSS 및 JavaScript의 역할은 다음과 같습니다. HTML은 컨텐츠 구조를 담당하고 CSS는 스타일을 담당하며 JavaScript는 동적 동작을 담당합니다. 1. HTML은 태그를 통해 웹 페이지 구조와 컨텐츠를 정의하여 의미를 보장합니다. 2. CSS는 선택기와 속성을 통해 웹 페이지 스타일을 제어하여 아름답고 읽기 쉽게 만듭니다. 3. JavaScript는 스크립트를 통해 웹 페이지 동작을 제어하여 동적 및 대화식 기능을 달성합니다.

HTML : 프로그래밍 언어입니까 아니면 다른 것입니까?HTML : 프로그래밍 언어입니까 아니면 다른 것입니까?Apr 15, 2025 am 12:13 AM

Htmlisnotaprogramminglanguage; itisamarkuplanguage.1) htmlstructuresandformatswebcontentusingtags.2) itworksporstylingandjavaScriptOfforIncincivity, WebDevelopment 향상.

HTML : 웹 페이지 구조 구축HTML : 웹 페이지 구조 구축Apr 14, 2025 am 12:14 AM

HTML은 웹 페이지 구조를 구축하는 초석입니다. 1. HTML은 컨텐츠 구조와 의미론 및 사용 등을 정의합니다. 태그. 2. SEO 효과를 향상시키기 위해 시맨틱 마커 등을 제공합니다. 3. 태그를 통한 사용자 상호 작용을 실현하려면 형식 검증에주의를 기울이십시오. 4. 자바 스크립트와 결합하여 동적 효과를 달성하기 위해 고급 요소를 사용하십시오. 5. 일반적인 오류에는 탈수 된 레이블과 인용되지 않은 속성 값이 포함되며 검증 도구가 필요합니다. 6. 최적화 전략에는 HTTP 요청 감소, HTML 압축, 시맨틱 태그 사용 등이 포함됩니다.

텍스트에서 웹 사이트로 : HTML의 힘텍스트에서 웹 사이트로 : HTML의 힘Apr 13, 2025 am 12:07 AM

HTML은 웹 페이지를 작성하는 데 사용되는 언어로, 태그 및 속성을 통해 웹 페이지 구조 및 컨텐츠를 정의합니다. 1) HTML과 같은 태그를 통해 문서 구조를 구성합니다. 2) 브라우저는 HTML을 구문 분석하여 DOM을 빌드하고 웹 페이지를 렌더링합니다. 3) 멀티미디어 기능을 향상시키는 HTML5의 새로운 기능. 4) 일반적인 오류에는 탈수 된 레이블과 인용되지 않은 속성 값이 포함됩니다. 5) 최적화 제안에는 시맨틱 태그 사용 및 파일 크기 감소가 포함됩니다.

HTML, CSS 및 JavaScript 이해 : 초보자 안내서HTML, CSS 및 JavaScript 이해 : 초보자 안내서Apr 12, 2025 am 12:02 AM

WebDevelopmentReliesonHtml, CSS 및 JavaScript : 1) HtmlStructuresContent, 2) CSSSTYLESIT, 및 3) JAVASCRIPTADDSINGINTERACTIVITY, BASISOFMODERNWEBEXPERIENCES를 형성합니다.

HTML의 역할 : 웹 컨텐츠 구조HTML의 역할 : 웹 컨텐츠 구조Apr 11, 2025 am 12:12 AM

HTML의 역할은 태그 및 속성을 통해 웹 페이지의 구조와 내용을 정의하는 것입니다. 1. HTML은 읽기 쉽고 이해하기 쉽게하는 태그를 통해 컨텐츠를 구성합니다. 2. 접근성 및 SEO와 같은 시맨틱 태그 등을 사용하십시오. 3. HTML 코드를 최적화하면 웹 페이지로드 속도 및 사용자 경험이 향상 될 수 있습니다.

HTML 및 코드 : 용어를 자세히 살펴 봅니다HTML 및 코드 : 용어를 자세히 살펴 봅니다Apr 10, 2025 am 09:28 AM

"Code"는 "Code"BroadlyIncludeLugageslikeJavaScriptandPyThonforFunctureS (htMlisAspecificTypeofCodeFocudecturecturingWebContent)

HTML, CSS 및 JavaScript : 웹 개발자를위한 필수 도구HTML, CSS 및 JavaScript : 웹 개발자를위한 필수 도구Apr 09, 2025 am 12:12 AM

HTML, CSS 및 JavaScript는 웹 개발의 세 가지 기둥입니다. 1. HTML은 웹 페이지 구조를 정의하고 등과 같은 태그를 사용합니다. 2. CSS는 색상, 글꼴 크기 등과 같은 선택기 및 속성을 사용하여 웹 페이지 스타일을 제어합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경