Skip to content

Latest commit

 

History

History
52 lines (45 loc) · 1.31 KB

code301-11.md

File metadata and controls

52 lines (45 loc) · 1.31 KB

<EJS %>

EJS (Embedded JavaScript templating): is a simple templating language that lets you generate HTML markup with plain JavaScript.

How to use EJS:

  1. install.
$ npm install ejs
  1. add it to JS file.
let ejs = require('ejs');
  1. use it to render data to html.
    • add pages/index.ejs to your repo.
app.set('view engine', 'ejs');
app.get('/', (req,res)=>{
    res.render('pages/index', {
        name: req.userName
    });
})
<h1> Hello <%= name %></h1>
let template = ejs.compile(str, options);
template(data);
// => Rendered HTML string
ejs.render(str, data, options);
// => Rendered HTML string
ejs.renderFile(filename, data, options, function(err, str){
    // str => Rendered HTML string
});

EJS Tags

  • <% 'Scriptlet' tag, for control-flow, no output
  • <%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
  • <%= Outputs the value into the template (HTML escaped)
  • <%- Outputs the unescaped value into the template
  • <%# Comment tag, no execution, no output
  • <%% Outputs a literal '<%'
  • %> Plain ending tag
  • -%> Trim-mode ('newline slurp') tag, trims following newline
  • _%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it