koa-views&&ejs

cnpm i ejs koa-views -S
  • 配置一(ejs文件)
const Koa = require("koa"),
  views = require("koa-views"),
  router = require("koa-router")();

const app = new Koa();

app.use(
  views("views", {
    extension: "ejs"
  })
);

router.get("/", async ctx => {
  await ctx.render("index");
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(8080);
  • 配置二(html文件)
app.use(
  views("views", {
    map: {
      html: "ejs"
    }
  })
);
  • 配置公共数据
const Koa = require("koa"),
  views = require("koa-views"),
  router = require("koa-router")();

const app = new Koa();

app.use(
  views("views", {
    map: {
      html: "ejs"
    }
  })
);

app.use(async (ctx, next) => {
  ctx.state.username = "JonSnow";
  await next(); //浙一这里不写await的话,页面出不来
});

router.get("/", async ctx => {
  await ctx.render("index");
});

router.get("/news", async ctx => {
  await ctx.render("news");
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(8080);
app.use(async (ctx, next) => {
  ctx.state = {
    name: "JonSnow",
    age: 21
  };
  await next(); //浙一这里不写await的话,页面出不来
});

  • 引入公共的html
    <% include components/header.ejs %>

按照视频上的写法,但是一直报错,还找不到问题


<% %>流程控制标签
<%= %>输出标签(原文输出HTML标签)
<%- %>输出标签(HTML)会被浏览器解析

router.get("/", async ctx => {
  await ctx.render("index", {
    title: "aaaa",
    list: ["a", "b", "c"],
    msg: "

aaa

", bool: false }); });
    

<%= title %>

    <% for(var i = 0;i< list.length;i++){ %>
  • <%= list[i] %>
  • <% } %>

<%= msg %>

<%- msg %>

<% if(bool){ %>

<%= title %>

<% }else { %>

<%= title + 1 %>

<% } %>

你可能感兴趣的:(koa-views&&ejs)