• express下ejs入门基础


    1.express中使用ejs

    var express = require('express');//需要安装 express
    
    var app = express();
    
    app.set("view engine","ejs");//模版引擎设置为 ejs

    2.文件组织

    在express中使用ejs,文件组织遵循express。
    
    .views-------放置动态模版
    
    .public------放置静态网页
    
    .layouts-----放置布局文件

    3.基本语法

    .<% code %>
    
        无缓冲的条件语句元素
    
    .<%= code %>
    
        转义HTML,该code并且会打印出来
    
    .<%- code %>
    
        非转义的buffering,该code并且会打印出来
    
    .<% include file %>
    
        内嵌别的文件
    
    .<% layout(file) -%>
    
        指定布局文件
    
    .<% script(file) -%>
    
        包含js脚本文件
    
    .<% stylesheet(file) -%>
    
        包含css文件
    
    .<% block(code, code) -%>
    
        指定块内容   

    4.基本对象

    .scripts
    
        包含的脚本
    
    .stylesheets
    
        包含的css
    
    .blocks
    
        包含的块

    5.这里是一个综合上述用法的例子

    主页面:

    //index.ejs
    <% layout('boilerplate') -%>
    <% script('foo.js') -%>
    <% stylesheet('foo.css') -%>
    <h1>I am the <%=what%> template</h1>
    <% block('header', "<p>I'm in the header.</p>") -%>
    <% block('footer', "<p>I'm in the footer.</p>") -%>

    布局文件:

    //boilerplate.ejs
    <!DOCTYPE html>
    <html>
      <head>
        <title>It's <%=who%></title>
        <%-scripts%>
        <%-stylesheets%>
      </head>
      <body>
        <header>
          <%-blocks.header%>
        </header>
        <section>
          <%-body -%>
        </section>
        <footer>
          <%-blocks.footer%>
        </footer>
      </body>
    </html>

    app.js中配置文件:

    //app.js
    var express = require('express')
      , engine = require('ejs-locals')
      , app = express();
    
    // use ejs-locals for all ejs templates:
    app.engine('ejs', engine);
    
    app.set('views',__dirname + '/views');
    app.set('view engine', 'ejs'); // so you can render('index')
    
    // render 'index' into 'boilerplate':
    app.get('/',function(req,res,next){
      res.render('index', { what: 'best', who: 'me' });
    });
    
    app.listen(3000);

    最后执行结果:

    <!DOCTYPE html>
    <html>
      <head>
        <title>It's me</title>
        <script src="foo.js"></script>
        <link rel="stylesheet" href="foo.css" />
      </head>
      <body>
        <header>
          <p>I'm in the header.</p>
        </header>
        <section>
          <h1>I am the best template</h1>
        </section>
        <footer>
          <p>I'm in the footer.</p>
        </footer>
      </body>
    </html>

    文章知识来自:这里,小北稍微改了改嘿嘿,改动不大。

  • 相关阅读:
    codevs 1202 求和
    codevs 1201 最小数和最大数
    nyist 240 小明的调查统计(二)
    nyist28大数阶乘
    nyist 626 intersection set
    【】小技巧】CSS文字两端对齐
    Vue.js项目模板搭建
    25个最基本的JavaScript面试问题及答案
    java抽象类与接口的区别及用法
    JQuery事件手册
  • 原文地址:https://www.cnblogs.com/stonl/p/4286756.html
Copyright © 2020-2023  润新知