简体   繁体   English

在没有 JS 框架的客户端渲染元素类名? (EJS)

[英]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.如果您的类名与类别不同但基于它,那么您只需要将查找对象传递给您的模板。

Server服务器

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);
});

Client客户

<% hobbies.forEach(hobby => { %>
    <div class="<%= lookup[hobby.category] %>"><%= hobby.name %></div>
<% }); %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EJS不在客户端渲染ejs代码 - EJS not rendering ejs code on client side ejs模板的客户端和服务器端渲染 - Client side and Server side rendering of ejs template ReactJS 服务器端渲染与客户端渲染 - ReactJS server-side rendering vs client-side rendering 如果通过XHR从客户端JS函数调用Express,则不会在浏览器中呈现页面 - Express is not rendering the page in the browser if called from a client-side JS function via XHR Node.js和Mustache.js:如何将服务器端渲染与客户端胡子模板分开? - Node.js & Mustache.js: How to separate server-side rendering than client-side mustache templating? 我应该在服务器端还是客户端渲染html? - Should I be rendering html on the server-side or client-side? 当我从客户端 js 调用服务器端 js 方法时,ejs 文件未使用 res.render 呈现 - ejs file not rendering with res.render when I call the server side js method from client side js 客户端超时Couchbase节点js - Client-Side timeout couchbase node js Node.js不更新客户端 - Node.js Not Updating Client-side 带有Node.js后端的移动应用-客户端开发人员应选择哪种框架? - Mobile app with Node.js backend - What framework to pick for client-side dev?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM