首页 > 解决方案 > 如何在 EJS 中设置动态样式属性?

问题描述

我正在使用 EJS 渲染引擎从 Node.js 发送邮件。我需要动态设置背景颜色、文本颜色和其他属性。

就像是style ="background: <%=primary_color%>"

或者如果我们可以动态选择类

class="<%=primary_class%>"

标签: htmlcssnode.jsejs

解决方案


您可以从 node.js express 服务器和ejs.renderFile.


//server.js

let bgColors = { 
  primary: '#000',
  accent: '#fff',
  gray: '#eee'
}

app.get('/', (req, res) => {
  ejs.renderFile('home.ejs', {bgColors}, {}, (err, template) => {
      if (err) throw err
      res.end(template)
  })
})

然后在 home html 文件中,您可以使用bgColors.


<div style="background: <%= bgColors.primary %>">Some text</div>

<div style="background: <%= bgColors.accent %>">Some more text</div>

<div style="background: <%= bgColors.gray %>">Some more text</div>


推荐阅读