最近几天我一直在寻找一个可行的解决方案来优化sails.js布局文件中的html页面标题<title>SOME_TITLE</title>,比如layout.ejs,默认使用静态页面标题.显然,拥有动态页面标题会更好,例如仪表板、购物车等... 其他人之前一直在寻找这个答案,并在 解决方案 1,解决方案 2 和 解决方案 3.不幸的是,它们似乎都不适合最新版本的sails.js(截至本文).解决方案 1 领先在正确的方向,并建议我正在寻找什么.但是您必须为每个控制器定义一个 title 并将其传递到视图中.否则你会得到
For the last few days I was looking for a viable solution in order to optimize html page titles <title>SOME_TITLE</title> within sails.js layout files, like layout.ejs, that by default use a static page title. Obviously, it would be way better to have dynamic page titles, e.g. Dashboard, Shopping Cart, etc... Other people were looking for this answer before and got answers for prior sails versions in Solution 1, Solution 2 and Solution 3. Unfortunately, none of them seem to be appropriate for the latest version of sails.js (as of this post). Solution 1 was leading in the right direction and suggested what I was looking for. But you had to define a title for every controller and pass it into the view. Otherwise you will get
标题未在 eval 中定义
title is not defined at eval
那么如何定义一个在每个控制器/视图中默认都可以访问的局部变量?
So how to define a local variable that is accessible in each controller/view by default?
推荐答案对于当前的sails.js 版本,一个可行的完整解决方案如下:
So one working complete solution for the current sails.js version is the following:
在你的 layout.ejs 文件中定义一个像这样的动态页面标题
In your layout.ejs file define a dynamic page title like this
<head> <title> <%= title %> </title> ... </head> ...创建一个新的自定义钩子,例如api/hooks/dynamic-page-title/index.js
Create a new custom hook, e.g. api/hooks/dynamic-page-title/index.js
module.exports = function dynamicPageTitleHook(sails) { return { routes: { /** * Runs before every matching route. * * @param {Ref} req * @param {Ref} res * @param {Function} next */ before: { '/*': { skipAssets: true, fn: async function(req, res, next){ // add page title variable to each response if (req.method === 'GET') { if (res.locals.title === undefined) { res.locals.title = 'plusX'; } } return next(); } } } } }; };现在覆盖应该使用自定义页面标题的每个控制器中的页面标题,例如view-login.ejs
Now overwrite the page title in every controller that should use a custom page title, e.g. view-login.ejs
module.exports = { friendlyName: 'View login', description: 'Display "Login" page.', exits: { success: { viewTemplatePath: 'pages/entrance/login', }, redirect: { description: 'The requesting user is already logged in.', responseType: 'redirect' } }, fn: async function (inputs, exits) { if (this.req.me) { throw {redirect: '/'}; } return exits.success({title: 'Login'}); } };更多推荐
如何在sails.js >v1.0中使用动态页面标题?
发布评论