EJS interpolation syntax : pass data to templates

refer to: https://www.udemy.com/course/the-web-developer-bootcamp/

https://ejs.co/#docs

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

example

 embed js in html(.ejs file)

<body>
    <h1>《出现又离开》<%= 0202 + 1%>
    </h1>
    <p>
        试探未知和未来 <br>
        相信那胡言一派 <br>
        当天空暗下来<br>
        当周围又安静起来<br>
        当我突然梦里醒来<br>
        就等着太阳出来<br>
    </p>
</body>

generate random number

random.ejs

<body>
    <h1>Your random number is : <%= Math.floor(Math.random()*10) + 1 %>
    </h1>
</body>
index.js

app.get('/random', (req, res) => { res.render('random.ejs') })

run nodemon index.js. ------>

the normaler way to use math: passing data to templates

index.js

app.get('/random', (req, res) => { const num = Math.floor(Math.random() * 10) + 1 res.render('random.ejs', {bubble: num}) })
random.ejs

<body>
    <h1>Your random number is : <%= bubble %>.  //match the object name defined in index.js
    </h1>
</body>
原文地址:https://www.cnblogs.com/LilyLiya/p/14365151.html