【问题标题】:How can I create a re-usable piece of markup in Jade如何在 Jade 中创建可重复使用的标记
【发布时间】:2012-12-05 03:18:06
【问题描述】:

我正在努力实现的目标。

我正在尝试做的实际上非常简单,Jade 模板引擎应该能够帮助我很多,但我遇到了一些障碍。

我正在构建一个使用很多半透明元素的网站,例如这个 jsFiddle 中的那个:http://jsfiddle.net/Chevex/UfKnM/
为了使容器背景半透明但保持文本不透明,这涉及到 3 个元素:

  • 带有position: relative 的容器DIV
  • 具有position: absolute、背景颜色、高度/宽度设置为 100% 且不透明度设置为所需级别的子 DIV。
  • 内容的另一个子 DIV,没有特殊定位。

它非常简单,我在CodeTunnel.com 上使用它相当有效。

我想如何简化它。

我正在用 node.js 重写 CodeTunnel.com,Jade 模板引擎似乎可以大大简化我一遍又一遍地重复使用的这段标记。 Jade mixins 看起来很有前途,所以我做了以下工作:

  1. 我定义了一个 mixin,所以我可以在任何需要的地方使用它。

    mixin container
        .container(id=attributes.id) // attributes is an implicit argument that contains any attributes passed in.
            .translucentFrame
            .contentFrame
                block // block is an implicit argument that contains all content from the block passed into the mixin.
    
  2. 使用mixin,传入一块内容:

    +container#myContainer
        h1 Some test content
    

    生成:

    <div id="myContainer" class="container">
        <div class="translucentFrame"></div>
        <div class="contentFrame">
            <h1>Some test content</h1>
        </div>
    </div>
    

到目前为止,一切都很好!只有一个问题。我想在 layout.jade 模板中使用这个 mixin,并且我希望子模板能够使用块继承。我的 layout.jade 文件如下所示:

doctype 5
mixin container
    .container(id=attributes.id)
        .translucentFrame
        .contentFrame
            block
html
    head
        title Container mixin text
    body
        +container#bodyContent
            block bodyContent

然后在另一个jade文件(index.jade)中扩展layout.jade:

extends layout

block bodyContent
    h1 Some test Content

一切看起来都井井有条,但玉解析器失败了:

我认为这与 block 关键字冲突有关。在 mixin block 内部是一个隐式参数,其中包含传递给 mixin 的块,但是当扩展一个玉模板块时,它是一个关键字,用于标识要在父模板中的等效块中替换的标记块。

如果我用任何其他标记替换我传递给 mixin 的 block bodyContent,那么一切正常。只有当我尝试传入块定义时,它才会感到不安。

有什么想法吗?

【问题讨论】:

  • 自您最初发布此内容以来有什么变化吗?即现在这行得通吗,还是有更好的方法?
  • @CodeBling 我认为这里没有太大变化。
  • 那太糟糕了。似乎将在 Jade 2 中解决的问题,should be released soonish

标签: javascript node.js view express pug


【解决方案1】:

我怀疑,因为mixins define their own functionsblock bodyContent 被定义在不同的范围内,无法从index.jade 访问。

您可以尝试将 mixin 的使用移至继承视图,因为 mixins are "hoisted":

layout.jade:

doctype 5

mixin container
    .container(id=attributes.id)
        .translucentFrame
        .contentFrame
            block

html
    head
        title Container mixin text
    body
        block bodyContent

index.jade:

extends layout

block bodyContent
    +container#myContainer
        h1 Some test content

【讨论】:

  • 是的,我可以这样做,然后我必须在每个继承视图上使用 mixin,因为我希望每个视图的 bodyContent 都包装在这个容器中。我想这没什么大不了的。我可以手动创建用于布局视图的元素(没有 mixin),然后在其他任何地方使用 mixin。
猜你喜欢
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 1970-01-01
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多