Jade 模板,包含的变量范围 [英] Jade templating, variable scope in includes

查看:37
本文介绍了Jade 模板,包含的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jade(没有 Express,仅用于静态 HTML 模板) - 我认为它能够创建部分,这意味着范围不是问题,但情况似乎并非如此,我找不到任何参考到这个用例.

ma​​ster.jade

<代码>!!!5html块变量- var slug = '家'头阻止页面标题标题静态 HTML链接(rel='样式表',href='css/styles.css')身体(类= 蛞蝓).wrapper包括包含/标题

includes/header.jade

.header超li(类= 蛞蝓)

我尝试过包括 #{slug} 在内的语法变体,但总是在 includes/header.jade 文件中收到错误slug 未定义" - 是否可能要这样做吗?

所以 Dave Weldon 在下面的评论中给出的答案是该变量在包含在 master.jade 中时可用,但我的构建命令编译了 all jade包括自身包含在内的文件,此时变量当然没有定义.

解决方案

你可以像这样使用 mixin 来完成这个:

master.jade

包含包含/标题!!!html块变量- var slug = '家'头阻止页面标题标题静态 HTML链接(rel='样式表',href='css/styles.css')身体(类= 蛞蝓).wrapper混合头(slug)

includes/header.jade

mixin header(klass).header超li(班级= klass)

编译时:

<头><title>静态 HTML</title><link rel="stylesheet" href="css/styles.css"><body class="home"><div class="wrapper"><div class="header"><ul><li class="home"></li>

</html>

I am using Jade (without Express, just for static HTML templating) - which I understood as able to create partials, meaning scope is not an issue, but this doesn't seem to be the case and I can find no reference to this use-case.

master.jade

!!! 5
html
  block vars
  - var slug= 'home'
  head
    block pagetitle
      title Static HTML
    link(rel='stylesheet', href='css/styles.css')
  body(class= slug)
    .wrapper
      include includes/header

includes/header.jade

.header 
  ul
    li(class= slug)

I have tried syntax variants including #{slug} and always get the error "slug is not defined" within the includes/header.jade file - is it possible to do this?

EDIT: So the answer as given by Dave Weldon in the comments below is that the variable is available when included in master.jade but my build command compiled all jade files including the includes on their own, at which point the variable is of course not defined.

解决方案

You could accomplish this with a mixin like so:

master.jade

include includes/header

!!!
html
  block vars
  - var slug= 'home'
  head
    block pagetitle
      title Static HTML
    link(rel='stylesheet', href='css/styles.css')
  body(class= slug)
    .wrapper
      mixin header(slug)

includes/header.jade

mixin header(klass)
  .header
    ul
      li(class= klass)

When compiled:

<!DOCTYPE html>
<html>
  <head>
    <title>Static HTML</title>
    <link rel="stylesheet" href="css/styles.css">
  </head>
  <body class="home">
    <div class="wrapper">
      <div class="header">
        <ul>
          <li class="home"></li>
        </ul>
      </div>
    </div>
  </body>
</html>

这篇关于Jade 模板,包含的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆