Express.js View “globals”

后端 未结 7 1644
太阳男子
太阳男子 2020-12-24 01:16

I\'m using Express.js (on Node.js) and I know that you can render a view with custom data via the \"locals\" parameter. (res.render(\"template\", { locals: { foo: \"ba

相关标签:
7条回答
  • 2020-12-24 01:54

    Express 4

    You can access local variables in templates rendered within the application.

    So, if you want to use any locals in your template => assuming you have a template engine npm installed to your node/express application.

    First, you need to set the express locals objects with your custom variables in your app.js file, you can use an object if multiple values are needed (our case in this post)

     /**
      *  Set locals object
      */
    
     app.locals.layoutData = { 
      site: {
          title: 'MyWebSiteTitle',
      },   
      metaTag: {
          charset: 'UTF-8',
          description: 'MyDescription',
          keywords: 'keyword-1,keyword-2,...',
          author: 'MyName',
          viewport: 'width=device-width, initial-scale=1.0'
      }
     };
    

    Then, to access the values in the template file layout.pug (in the case of PUG template engine for instance)

    doctype html
    html
      head
        //title
        title #{locals.layoutData.site.title}
        //Describe metadata
        meta(charset=layoutData.metaTag.charset)
        meta(name='description', content=locals.layoutData.metaTag.description)
        meta(name='keywords', content=locals.layoutData.metaTag.keywords)
        meta(name='author', content=locals.layoutData.metaTag.author)
        meta(name='viewport', content=locals.layoutData.metaTag.viewport)
      body
          block content
          br
          hr
          footer
            p All rights reserved © 2018 |  #{locals.layoutData.site.title}
    

    Tested with

      "dependencies": {
        "express": "^4.16.3",
        "pug": "^2.0.3"
      }
    
    0 讨论(0)
提交回复
热议问题