簡體   English   中英

動態設置元標簽 EJS

[英]Dynamically set meta tags EJS

我正在使用 EJS,我需要為每個帖子設置元標記。 我在 layouts 文件夾中有樣板文件,我將其包含在每一頁中。 當用戶進入發帖頁面時,我需要設置動態元標簽和標題。 我的樣板

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= title %></title>
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
    <% include ../partials/navbar.ejs %>
    <div class="container-fluid">
        <% include ../partials/filter.ejs %>
        <div class="row">
            <div class="col-sm-12 col-lg-10">
                <%- body -%>
            </div>
            <div class="col-sm-12 col-lg-2">
                <% include ../partials/sidebar %>
            </div>
        </div>
    </div>
</body>
</html>

我正在嘗試以這種方式將標題傳遞給發布頁面

res.render('post/index', {title: post.meta.title, post: post});

但是我有一個錯誤,即樣板中沒有定義標題;

如果我正確理解了這個問題,我為你做了一個樣本。

帖子的 mongoose 架構

const postScheme = new Schema({
 "title": String, 
 "description": String, // meta description
 "robots": String, // index or noindex
 "lang": String, // en, fr, tr
 "pathname": String, // post-pathname
 "main": String // post body content
})

獲取帖子數據並渲染。

Post.findOne({ _id: req.params.id }, (err, data) => {
  res.render('post/index', { 'data': data })
}).lean()

並編輯.ejs 文件。

<!doctype html>
<html lang="<%= data.lang %>">
<head>
    <meta charset="UTF-8">
    <title> <%= data.title %> </title>
    <meta name="description" content=" <%= data.description %> "/>
    <link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
    <% include ../partials/navbar.ejs %>
    <div class="container-fluid">
        <% include ../partials/filter.ejs %>
        <div class="row">
            <div class="col-sm-12 col-lg-10">
                <%- data.main %>
            </div>
            <div class="col-sm-12 col-lg-2">
                <% include ../partials/sidebar %>
            </div>
        </div>
    </div>
</body>
</html>

您是否在所有頁面中呈現title變量? 如果不是這就是為什么你得到未定義的錯誤。 使用locals object 檢查未定義並將您的變量包含在標題 html 標記中。
如果您不呈現標題變量,您可以為頁面的 rest 設置通用標題

<title> <%= locals.title ? title  : 'Α generic title' %> </title>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM