簡體   English   中英

使用服務器端的變量將 CSS 文件添加到 ejs 模板

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

我正在嘗試在 ejs 模板中動態添加 css 文件。

我知道如何包含 ejs 文件,但不知道如何動態添加 css 文件。

代碼 :-

索引.js

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

模板.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>

我試過 :

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

目標:

在樣式表源中傳遞服務器端接收到的變量(cssa)。

不需要concat css路徑和變量,你也可以這樣做:

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

方法包括:

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

歸功於@SpiRT

或者 :

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

我發現通過數組注入自定義 css 腳本最方便,然后可以在 ejs 模板中進行處理。

此方法將允許您呈現額外需要的任意數量的 CSS 文件(例如,您有一個站點,它在所有頁面上使用 1 個標准 css,但有 1 或 2 個頁面特定的,然后可以包含在通過ejs 渲染器到該特定頁面/路由)。 在示例中,css 文件位於同一個文件夾中,但是可以根據每個人的喜好進行更改:

路由器端:

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

將自定義樣式表推送到視圖后,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