简体   繁体   中英

Adding CSS File to ejs tempelate using variable from server side

I am trying to add css file dynamically in ejs tempelate.

I know how to include ejs file but not getting how to add css file dynamically.

Code :-

Index.js

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

template.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.

不需要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

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.

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). 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:

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:

<% 
    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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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