gpt4 book ai didi

layout - 在marko模板中全局访问变量

转载 作者:行者123 更新时间:2023-12-04 00:47:25 25 4
gpt4 key购买 nike

我们在nodejs应用程序中使用marko模板引擎。我们有 3 个 Marko 布局

  1. 标题.marko
  2. 布局.marko
  3. 页脚.marko

页眉和页脚布局在layout.marko内渲染

每当我们创建一个新的 marko 页面(内容页面)时,我们都会使用这样的布局 marko

<layout-use template="./../layout.marko">

并像这样加载marko

this.body = marko.load("./views/home.marko").stream(data);

现在我们想要访问全局变量。即如果我们有一个变量 username='abc'。我们想要在 header、layout 或 footer marko 文件中访问并显示这个名称。但我们不想为每个内容标记页面传递用户名。即,如果我们网站上有 100 个页面,我们不希望传递所有 100 个页面的用户名。每当用户登录时,将用户名保存在全局变量中,并在所有页面中使用此全局变量。

我们如何实现这个全局变量功能。

最佳答案

看起来您可以使用 $global暴露数据的属性适用于所有模板。

例如:

router.get('/test', function * () {
this.type = 'html'
this.body = marko.load("./views/home.marko")
.stream({
color: 'red',
$global: {
currUser: { id: 2, username: 'hansel' }
}
})
})

然后是这些模板:

// home.marko
<include('./header.marko') />
<h1>color is ${data.color}</h1>

// header.marko
<h2>Header</h2>
<p if(out.global.currUser)>
Logged in as ${out.global.currUser.username}
</p>
<p else>
Not logged in
</p>

这有效。

但显然你不想必须通过 $global进入每.stream() ,所以一个想法是将其存储在 Koa 上下文中,让任何中间件将数据附加到它,然后编写一个帮助程序将其传递到我们的模板。

// initialize the object early so other middleware can use it
// and define a helper, this.stream(templatePath, data) that will
// pass $global in for us
router.use(function * (next) {
this.global = {}
this.stream = function (path, data) {
data.$global = this.global
return marko.load(path).stream(data)
}
yield next
})

// here is an example of middleware that might load a current user
// from the database and attach it for all templates to access
router.use(function * (next) {
this.global.currUser = {
id: 2,
username: 'hansel'
}
yield next
})

// now in our route we can call the helper we defined,
// and pass any additional data
router.get('/test', function * () {
this.type = 'html'
this.body = this.stream('./views/home.marko', {
color: red
})
})

该代码适用于我上面定义的模板:${out.global.currUser}可以从 header.marko 访问,但是 ${data.color}可以从以下位置访问主页.马科。

我从未使用过 Marko,但我很好奇,在看到后阅读了文档你的问题是因为我时常想到使用它。我没感觉到就像弄清楚如何<layout-use>有效,所以我用了 <include>相反。

关于layout - 在marko模板中全局访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40046904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com