Nunjuks foundation 1 (Xiaozhou report notes)

Posted by zuperxtreme on Wed, 05 Jan 2022 18:51:40 +0100

A web server is created through Koa and can respond to different pages according to different user request paths. However, the content of each page is sent to the browser in the form of string. This development method is not friendly. We prefer to send html pages directly.

The template engine can solve this problem. Through the template engine, you can directly set the html page of the response, bind the background data to the template, and then send it to the client.

const Koa = require("koa");  
const nunjucks = require("nunjucks");
const views = require("koa-views");
const app = new Koa();  

app.use(views(__dirname + '/views', {
    //Files with html suffixes will be rendered using the nunjuks template engine.
    map: { html: 'nunjucks' } 
}));

app.use(async ctx => {
    //The render method renders the template, and the second parameter can pass parameters to the template
    await ctx.render("index",{title:"My first template"}) 
})

app.listen(3000, () => {
    console.log("server is running");
}) 

Template files (html files) written in the view folder

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{{title}}</title>
</head>
<body>
    <h1>hello world</h1>
</body>
</html>

app.use(views(__dirname + '/views', {
//Files with html suffixes will be rendered using the nunjuks template engine.
map: { html: 'nunjucks' }
}));
This method has two parameters: one specifies the directory in which the template engine is located (in fact, a standard html is stored in the directory), and the second specifies the template engine

The template is rendered using the render method, and the second parameter can be passed to the template

const router = require("koa-router")();
const Koa = require("koa");
const nunjucks = require("nunjucks");
const views = require("koa-views");

const app = new Koa();

app.use(views(__dirname + '/views', {
    //Files with html suffixes will be rendered using the nunjuks template engine.
    map: { html: 'nunjucks' }
}));

router.get('/', async (ctx, next) => {
    await ctx.render('index', {
        title: "Welcome to Xiaozhou report"
    })
});

router.get('/docs', async (ctx, next) => {
    await ctx.render('index', {
        title: 'Xiaozhou Report',
        desc: 'Make learning more efficient'
    })
});

app.use(router.routes())


app.listen(3000, () => {
    console.log("server is running");
})

Both get methods load an html(index), but can display two pages.
I wrote an html as a template, which can be used as two pages. Good, good.

The form sends data to the background. First, look at the properties of the two form tags.
action attribute: Specifies the path of data submitted by the form
Method attribute: Specifies the request method for submitting data from the form. The request methods include get and post.
get will carry it on the url, but post will not.

After setting the form label, set the form space
input.name attribute: Specifies the field (key) for data transmission
input.type = "submit": specify the submit button and click to submit the form data

router.get("/data", async ctx => {
    let username = ctx.query.username;
    await ctx.render("home", { usr: username })
})

Get the data requested by get
The example code is as follows:

const router = require("koa-router")();
const Koa = require("koa");
const nunjucks = require("nunjucks");
const views = require("koa-views");

const app = new Koa();

app.use(views(__dirname + '/views', {
    //Files with html suffixes will be rendered using the nunjuks template engine.
    map: { html: 'nunjucks' }
}));
app.use(async (ctx, next) => {
    await ctx.render("index");
    await next();
})


//Get parameters of get request

router.get("/login", async ctx => {
    let username = ctx.query.username;
    let password = ctx.query.password;
    await ctx.render("home", {
        username: username,
        password: password
    })
})

app.use(router.routes())


app.listen(3000, () => {
    console.log("server is running");
})

index.html

<body>
    <form action="/login" method="GET">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="submit" value="Sign in">
    </form>

</body>

home.html

<body>
    <p>user name:{{username}}</p>
    <p>password:{{password}}</p>
</body>

Directly through CTX Query can get the data requested by get,

If you need to obtain the data of the post request, you need to install the third-party module koa parser to parse the post request. The example code is as follows:

const router = require("koa-router")();
const Koa = require("koa");
const nunjucks = require("nunjucks");
const views = require("koa-views");
const parser = require('koa-parser')

const app = new Koa();
app.use(parser());

app.use(views(__dirname + '/views', {
    //Files with html suffixes will be rendered using the nunjuks template engine.
    map: { html: 'nunjucks' }
}));
app.use(async (ctx, next) => {
    await ctx.render("index");
    await next();
})

//Get parameters of Post request
router.post("/login", async ctx => {
    let username = ctx.request.body.username;
    let password = ctx.request.body.password;
    await ctx.render("home", {
        username: username,
        password: password
    })
})

app.use(router.routes())

app.listen(3000, () => {
    console.log("server is running");
})

Learning video
https://www.bilibili.com/video/BV1zf4y1r711?p=8&share_source=copy_web

Topics: Front-end