如何使用三元运算符将类添加到ejs中的HTML元素 [英] How to use a ternary operator to add a class to an HTML element in ejs
问题描述
我是使用ejs的新手.我有一个菜单,我想突出显示当前菜单项.我已经尝试过了:
I am new to using ejs. I have a menu and I want to highlight the current menu item. I have tried this:
<li class=<% currentMenu == 'dashboard' ? 'active' : ''%>>
<a href= '/dashboard'>
<i class="material-icons">dashboard</i>
<span>Dashboard</span>
</a>
</li>
currentMenu的值由快递路由器提供,如下所示:
The value of the currentMenu is served by an express router as shown below:
app.get('/dashboard', function(req, res) {
if (isAuthorised) {
res.render('pages/index', {
title: 'Welcome | MW Tracker',
email, userName, role, menus,
currentMenu: 'dashboard'
})
} else {
res.render('pages/sign-in', {
title: 'Sign In | MW Tracker'
})
}
});
请问我应该如何添加课程?
Please how am I suppose to add the class?
推荐答案
您需要将<%%>
标记替换为<%=%>
标记以输出表达式值:
You need to replace the <% %>
tag with the <%= %>
tag in order to output the expression value:
<li class="<%= currentMenu === 'dashboard' ? 'active' : '' %>">
<!-- -->
</li>
如 EJS文档所述,<%%>
标记用于控制流,无输出代码;而<%=%>
标记会输出并将值插值到HTML模板中.
As the EJS documentation states, the <% %>
tags are for control-flow, no output code; whereas the <%= %>
tags output and interpolate the value into the HTML template.
例如,下面的 if
语句使用<%%>
标记,因为该语句不需要输出到HTML中.然后在条件内部,使用<%=%>
标签将变量输出并内插到HTML模板中:<%= currentMenu%>
For example, the if
statement below uses <% %>
tags because the statement doesn't need to be outputted into the HTML. Then inside of the condition, the variable is outputted and interpolated into the HTML template by using the <%= %>
tags: <%= currentMenu %>
.
<% if (currentMenu === 'dashboard') { %>
<span><%= currentMenu %></span>
<% } %>
这篇关于如何使用三元运算符将类添加到ejs中的HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!