javascript - 如何在 Jade 中创建可重用的标记

标签 javascript node.js view express pug

我想要完成的事情。

我想做的事情实际上非常简单,Jade 模板引擎应该能够帮我解决很多问题,但我遇到了一些障碍。

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

  • position: relative 的容器 DIV
  • position: absolute 的子 DIV,背景颜色,高度/宽度设置为 100%,其不透明度设置为所需级别。
  • 没有特殊定位的内容的另一个子 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,传入一个内容 block :

    +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,我希望子模板能够使用 block 继承。我的 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 的 block 的隐式参数,但是当扩展 jade 模板时, block 是一个关键字,用于标识要在等效 block 中替换的标记 block 父模板。

如果我用任何其他标记替换我传递到混合中的 block bodyContent,那么一切正常。只有当我尝试传递一个 block 定义时,它才会生气。

有什么想法吗?

最佳答案

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

您可以尝试的是将 mixin 的使用移至继承 View ,因为 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

关于javascript - 如何在 Jade 中创建可重用的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13924133/

相关文章:

javascript - 如何使用javascript在上传图像时显示图像

javascript - jquery ajax 简单的 post/get

javascript - 使用 d3.js 对 .svg 文件中的路径进行动画处理

javascript - 将信息从 javascript 传递到使用 php 查询数据库时出错

node.js - twilio 操作 url 中的查询参数

ios - iPad 中的 UIActionSheet 底部带有箭头

node.js - 使用一个 bash 脚本运行两台 Node 服务器并接收控制台日志

node.js - IntelliJ : Lost files after "Update project" and can't find them on Local history

javascript - 模型属性未统一命名的 Backbone 集合和模板

mysql - If 语句并选择一行