javascript 动态设置 meta标签EJS

5ktev3wc  于 2023-04-28  发布在  Java
关注(0)|答案(2)|浏览(298)

我正在使用EJS,我需要为每个职位设置 meta标签。我在layouts文件夹中有样板文件,我在每个页面上都包含了它。当用户进入发帖页面时,我需要设置动态 meta标签和标题。我的样板

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

但是我有一个错误,标题没有在样板文件中定义;

xt0899hw

xt0899hw1#

如果我理解正确的话,我给你做了一个样品。
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>
dz6r00yl

dz6r00yl2#

是否在所有页面中呈现title变量?如果没有,这就是为什么你得到undefined错误。用locals对象检查undefined,并将变量包含在title html标签中。
如果您不呈现标题变量,您可以为其余页面设置通用标题

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

相关问题