如何在sails.js >v1.0中使用动态页面标题?

编程入门 行业动态 更新时间:2024-10-17 12:24:39
本文介绍了如何在sails.js >v1.0中使用动态页面标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

最近几天我一直在寻找一个可行的解决方案来优化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 &gt;v1.0中使用动态页面标题?

本文发布于:2023-11-07 05:57:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565715.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:页面   标题   动态   如何在   sails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!