ikcamp| build node. js combat (with video) based on KOA2? View Nunjucks

Source: Internet
Author: User

Video Address: https://www.cctalk.com/v/15114923888328

View Nunjucks

The Rainbow is the Covenant of God and Man, and God will not use the flood to extinguish the man.

The " template engine " needs to be used when the client and the server communicate with each other, and the data that is passed is eventually displayed in the view.

What is a template engine?

The template engine is created to separate the user interface from the business data and can generate documents in a specific format. For example, the template engine for a Web site generates a standard HTML document.

There are many common template engines on the market, such as:,,, Smarty Jade Ejs Nunjucks etc., can be selected according to personal preferences. koa-views, and koa-nunjucks-2 other supported Koa third-party middleware can also be selected by themselves.

In this project, we use it koa-nunjucks-2 as a template engine. Nunjucksis a Mozilla developed, purely js written template engine that can be used either in the Node environment or on the browser side. koa-nunjucks-2is based on Nunjucks the encapsulated third-party middleware, perfect support Koa2 .

Nunjucks Introduction

First we need to understand Nunjucks a few features

Simple syntax

Variable

  {{}}  {{foo.bar}}  {{ foo["bar"}}

If the value of the variable is undefined or null , it will not be displayed.

Filter filters

  {{|}}  {{|join(","}}  {{|replace("foo","bar"|}}

ifJudge

  {%if%}    true  {%%}  {%if%}    I am hungry  {%%}    I am tired  {%else%}    I am good!  {%%}

forCycle

 var  items =  [{ title  :   "foo"  Span class= "Op",  id  :  1   { title  :    id  :  2  } ]  
  <h1>Posts</h1>  <ul>  {% for item in items %}    <li>{{ item.title }}</li>  {%else%}    <li>if‘item‘ collection were empty</li>  {% endfor %}  </ul>

macroMacro

Macro: Defines reusable content, similar to a function in a programming language

  {%field(name, value=‘‘, type=‘text‘%}  <class="field">    <input type="{{ type }}" name="{{ name }}"          value="{{ value | escape }}"/>  </div>  {%%}

You can then field use the same as a function:

  {{field(‘user‘}}  {{field(‘pass‘, type=‘password‘}}

For more syntax, please refer to the official documentation

Inheritance Features

The most common structure of web pages is the head, intermediate and tail, multiple pages under the same website, the head and tail content is generally consistent. So we can use the inheritance function to write.

First define alayout.html

  <Html>    <Head>      {%Block Head%}      <Link rel="stylesheet">      {%Endblock%}    </head><body>{% block header%}>      {%Endblock%}      {%Block body%}      <H1> Thisis body</h1>{% Endblock%}{% block footer%}>        {%Endblock%}      {%Block content%}      <Script>        //this is place for JavaScript      </script>{% Endblock%}</body>  </html>

layoutFive modules are defined, named:,,, head , header body footer content . headerand footer are common, so basically not moving. Changes to the business code need to body be made only in the content body, business style sheets, and business scripts are introduced in the header head and the bottom respectively content .

Next we define a business-level view page:home.html

  {% extends ‘layout.html‘ %}  {% block head %}  <link href="home.css">  {% endblock %}  {% block body %}  home 页面内容  {% endblock %}  {% block content %}  <script src="home.js"></script>  {% endblock%}

The final home.html output is as follows:

            <link href="home.css">          <body>      this is header      home 页面内容      this is footer        <script src="home.js"></script>    </body>  
Security

Please escape the special characters to prevent Xss attack. If this type of string variable is written on the page Hello World<script>alert(0)</script> and is not escaped, the script executes automatically when the page renders, and a popup box pops up.

Install and run

Installation koa-nunjucks-2 :

npm i koa-nunjucks-2-S

Modify app.js , introduce middleware, and specify the directory where the view files are stored views :

  ConstKoa= require(' KOA ')ConstPath= require(' path ')ConstBodyparser= require(' Koa-bodyparser ')ConstNunjucks= require(' Koa-nunjucks-2 ')ConstApp= New Koa()ConstRouter= require('./router ')app. Use(Nunjucks({    ext: ' HTML ',    Path: Path.Join(__dirname, ' views '),//Specify the View directory    Nunjucksconfig: {      Trimblocks: true //Turn on escape anti-XSS    }  }));  app. Use(Bodyparser())Router(APP)app.Listen( the,()= {    Console.Log(' server is running at http://localhost:3000 ')})

In the previous project, the view was written in controller/home , and now we move it into views :

New views/home/login.html :

  <! DOCTYPEHtml>  lang="en">      <title></title>    <metacharset="UTF-8">    <metaname="Viewport"content="Width=device-width, initial-scale=1">    <body>    <formaction="/user/register"method="POST">      <inputname="Name"type="Text"placeholder="Please enter user name: Ikcamp" />      <br/>      <inputname="Password"type="Text"placeholder="Please enter password: 123456" />      <br/>      <button>{{Btnname}}</button>    </form>  </body>  

controller/homemethods in the override login :

  login:async(ctx,=>{    ctx.render(‘home/login‘,{      btnName:‘GoGoGo‘    })  },

Note: Here we used await to read the file asynchronously. Because you need to wait, you must ensure that the file is read before the requested response is made.

After adding views layers, the view function is not perfect, and we need to add a static resource directory. Of course, it would be better if you could use a static server directly. In the next section, we'll cover how to add static files and beautify the project view.

Next: Handling static resources-specifying the static file directory, setting the cache

Previous: Ikcamp new courses launched ~~~~~ikcamp| based on KOA2 to build node. js combat (including video)? Code layering

Recommendation: Translation Project Master's Readme: 1. Dry Goods | Everyone is a Master2 of translation projects. Ikcamp Small Program Teaching Total 5 Chapters 16 sections summary (including video)

ikcamp| build node. js combat (with video) based on KOA2? View Nunjucks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.