[英]Rendering elements classname in client-side without JS framework? (EJS)
Let's say I have an app which shows to the users a list of existing hobbies.假设我有一个应用程序,它向用户显示现有爱好的列表。
Each hobby has a category, stored in the db.每个爱好都有一个类别,存储在数据库中。
I want every hobby element to have its background color - dependent on its category.我希望每个爱好元素都有其背景颜色 - 取决于其类别。
I want to implement this with appending specific class to each element.我想通过将特定的类附加到每个元素来实现这一点。
Basic example code:基本示例代码:
Server服务器
app.get("/hobbies", (req, res) => {
const hobbies = Hobby.getAllHobbies();
res.render("hobbies", hobbies);
});
Client (EJS)客户端 (EJS)
<% hobbies.forEach(hobby => { %>
<div class=""><%= hobby.name %></div>
<% }); %>
What is the best way to append to each div a class depending of hobby.category?根据 hobby.category 为每个 div 添加一个类的最佳方法是什么?
I know its easily possible in React, but I don't want to use any framework for now.我知道它在 React 中很容易实现,但我现在不想使用任何框架。
If your classname is not the same as the category but is based on it, then you just need to pass a lookup object to your template.如果您的类名与类别不同但基于它,那么您只需要将查找对象传递给您的模板。
const categories_classnames = {
lookup: {
swimming: 'div-swim',
biking: 'div-bike',
painting: 'div-paint',
// ...
}
};
app.get("/hobbies", (req, res) => {
const hobbies = Hobby.getAllHobbies();
// Alternatively, `locals = { ...hobbies, ...categories_classnames }`
const locals = Object.assign({}, hobbies, categories_classnames);
res.render("hobbies", locals);
});
<% hobbies.forEach(hobby => { %>
<div class="<%= lookup[hobby.category] %>"><%= hobby.name %></div>
<% }); %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.