如何在Jade中创建一个可重复使用的标记

Che*_*hev 5 javascript view node.js express pug

我正在努力实现的目标.

我想要做的实际上非常简单,Jade模板引擎应该可以帮助我很多,但我遇到了一些障碍.

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

  • 一个容器DIV用 position: relative
  • 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.
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用mixin,传入一个内容块:

    +container#myContainer
        h1 Some test content
    
    Run Code Online (Sandbox Code Playgroud)

    产生:

    <div id="myContainer" class="container">
        <div class="translucentFrame"></div>
        <div class="contentFrame">
            <h1>Some test content</h1>
        </div>
    </div>
    
    Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很棒!只有一个问题.我想在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
Run Code Online (Sandbox Code Playgroud)

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

extends layout

block bodyContent
    h1 Some test Content
Run Code Online (Sandbox Code Playgroud)

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

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

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

有任何想法吗?

Jon*_*ski 6

我怀疑,因为mixins定义了自己的函数,所以block bodyContent在不同的范围内定义了不可访问的函数index.jade.

你可以尝试的是将mixin的使用转移到继承视图,因为mixins被"提升":

layout.jade:

doctype 5

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

html
    head
        title Container mixin text
    body
        block bodyContent
Run Code Online (Sandbox Code Playgroud)

index.jade:

extends layout

block bodyContent
    +container#myContainer
        h1 Some test content
Run Code Online (Sandbox Code Playgroud)