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

5

我想要实现的目标。

我的目标其实非常简单,Jade模板引擎应该可以帮助我很多,但是我遇到了一些问题。

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

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

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

我想要简化它。

我正在使用node.js重新编写CodeTunnel.com,Jade模板引擎似乎可以极大地简化我反复重用的这段标记。Jade混合功能看起来很有前途,所以我做了以下操作:

  1. I defined a mixin so I could just use it wherever I need it.

    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. Use the mixin, passing in a block of content:

    +container#myContainer
        h1 Some test content
    

    Generates:

    <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

一切看起来都很正常,但jade解析器失败了:

我猜想这可能与block关键字的冲突有关。在mixin内部,block是一个隐含的参数,其中包含传递到mixin中的块,但是当扩展jade模板时,block是一个关键字,用于标识要替换父模板中等效块中的标记块。
如果我将传递到mixin中的block bodyContent替换为任何其他标记,则一切正常。只有当我尝试传递块定义时,它才会出现问题。
有什么想法吗?

自您最初发布此内容以来,有什么变化吗?即现在是否有效,或者是否有更好的方法? - Codebling
@CodeBling 我不认为这里有太多变化。 - Chev
太糟糕了。看起来这是Jade 2即将解决的问题,应该很快发布 - Codebling
1个回答

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

index.jade:

extends layout

block bodyContent
    +container#myContainer
        h1 Some test content

是的,我可以做到,只需要在每个继承的视图上使用mixin,因为我希望每个视图的bodyContent都包含在这个容器中。我想这并不是很麻烦。我可以手动创建元素(而不使用mixin)用于布局视图中,然后在其他地方使用mixin。 - Chev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接