简体   繁体   English

使用服务器端的变量将 CSS 文件添加到 ejs 模板

[英]Adding CSS File to ejs tempelate using variable from server side

I am trying to add css file dynamically in ejs tempelate.我正在尝试在 ejs 模板中动态添加 css 文件。

I know how to include ejs file but not getting how to add css file dynamically.我知道如何包含 ejs 文件,但不知道如何动态添加 css 文件。

Code :-代码 :-

Index.js索引.js

router.get('/', function(req, res, next) {
  res.render('template', { title: 'abc',page:'index',cssa:'home'});
});

template.ejs模板.ejs

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="/stylesheets/style.css">
    <!-- Here I want to add home.css file -->
  </head>
  <body>
   <!-- including my ejs file -->
   <%- include(page) %>
  </body>
</html>

I tried :我试过 :

<link rel="stylesheet" type="text/css" href="/stylesheets/\<%= cssa %>\" >
<% include %><%= cssa %><% .css %>

Goal:目标:

to pass the server side received variable(cssa) in stylesheet source.在样式表源中传递服务器端接收到的变量(cssa)。

不需要concat css路径和变量,你也可以这样做:

<link rel='stylesheet' href='/stylesheets/<%= yourVariableName %>.css' />

Method to include :方法包括:

<% var css_link = '/stylesheets/' + cssa + '.css'; %>
<link rel="stylesheet" type="text/css" href="<%= css_link %>" >

Credit goes to @SpiRT归功于@SpiRT

Alternatively :或者 :

<link rel="stylesheet" type="text/css" href="/stylesheets/<%=cssa%>.css">

I've found it most convenient to inject custom css scripts through an array which can then be processed in the ejs template.我发现通过数组注入自定义 css 脚本最方便,然后可以在 ejs 模板中进行处理。

This method would allow you to render any amount of CSS files that are additionally required (example, you have a site that uses 1 standard css across all pages but have 1 or 2 page specific ones which can then be included in the model passed through the ejs renderer to that specific page/route).此方法将允许您呈现额外需要的任意数量的 CSS 文件(例如,您有一个站点,它在所有页面上使用 1 个标准 css,但有 1 或 2 个页面特定的,然后可以包含在通过ejs 渲染器到该特定页面/路由)。 In the example it's a given that the css files are in the same folder, however that can be changed to each one's liking:在示例中,css 文件位于同一个文件夹中,但是可以根据每个人的喜好进行更改:

router side:路由器端:

router.get( ... {
    model = {};
    model.Stylesheets = [];
    model.Stylesheets.push("stylefile");
    res.render("view",{model:model});
});

with the custom stylesheets being pushed though to the view, then the ejs files can be something like:将自定义样式表推送到视图后,ejs 文件可能类似于:

<% 
    var customStylesheets = "";

    model.Stylesheets.forEach(function(style){
        customStylesheets+='<link type="text/css" rel="stylesheet" href="css/'+style+'.css">';
    })

%>

<!DOCTYPE html>
<html>

<head>
    <title><%= model.title %></title>
    <link type="text/css" rel="stylesheet" href="css/standard.css">
    <%- customStylesheets %>
...
</head>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM