I
I
It2020-05-04 14:25:16
Node.js
It, 2020-05-04 14:25:16

How to display a block in an express.js template depending on the presence of the locals property?

Good day everyone. There is a site on a node + express js. According to the standard, there is index.js in routes, and there is a template for displaying typical pages.
In the template in head the following construction:

<!DOCTYPE html>
<html class="no-js" lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="<%= locals.meta_description %>">
        <title><%= locals.title %></title>
        <link rel="canonical" href="https://www.site<%= locals.canonical_link %>">


The following properties are written in the index for each page:
router.get('/page-1', function (req, res) {
    res.render('page-template', {
        layout: 'layout',
        title: 'Title1',
        template: 'page',
        canonical_link: '/page-1',
        meta_description: 'Descr-1'
    });
});


If you do not specify canonical_link: '/page-1' in the route, then an error pops up. Actually, the question is how to correctly check for the presence of the canonical_link property in the route for a specific page, and if the property exists, then output a string when rendering is normal, and if there is no such property, then do not display a line in the head at all
<link rel="canonical" href="https.....>.

Tried checks for udefined and obj ?. prop, but something does not come out at all, apparently there are problems with understanding how these methods work.

I will be grateful for a piece of code in general, a thousand likes, marks about the solution and other possible goodies

)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question