【问题标题】:How to pass an object's properties as the locals to an include in Jade?如何将对象的属性作为本地人传递给 Jade 中的包含?
【发布时间】:2012-05-01 14:52:20
【问题描述】:

我想在循环中传递一个对象,如下所示;

数据结构:

things = [
      {
          title: 'foo'
        , description: 'bar'
      }
    , {
          title: 'baz'
        , description: 'bam'
      }
];

index.jade:

- for thing in things
    include things-template

在上述格式中,我希望能够将某种参数指定为该包含的“本地”。

things-template.jade:

li
  h3 #{title}
  p #{description}

这可能吗,还是我需要将它分配给另一个变量并在我的“事物模板”中引用它?

【问题讨论】:

  • 我强烈建议您采用 JSLint 规定的语法...
  • 具体是什么,+Ates Goral?
  • 我只是说大括号和逗号的放置不是很传统。如果您曾经想过采用不同的风格,我建议您坚持 Crockford(或 JSLint)规定的风格。您会经常在 OSS 项目中看到这种风格。它也非常类似于 Sun Java 风格。使用传统风格有助于与其他人合作......
  • @Martindale,我也很想要这个功能,但我不相信它会出现...... :(

标签: javascript templates template-engine pug


【解决方案1】:

作为最新的翡翠版本(0.27.4)
您可以将对象引用作为模板的同名传递

for thing in things
  include thing

将自动将 ./thing.jade 包含为对象
在thing.jade:

li
  h3 #{thing.title}
  p #{thing.description}

【讨论】:

  • 问题在于 things-template.jade 本身就很有用。通过指定“thing.title”而不是“title”,您需要更改在自己渲染时传递的本地变量。
  • 对我不起作用。我收到一条错误消息no such file ... thing template。在我的情况下,thing 应该是模板的字符串路径。相反,jade 认为模板本身被称为thing
【解决方案2】:

由于您想包含现有模板,我猜您没有这么多。为什么不简单地使用 àjadecase 块?

html
    body
        for thing in things
            case things-template
                when "simple"
                    include simple
                when "complexe"
                    include complexe
                default
                    include simple

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-03
    • 2020-11-05
    • 2016-06-06
    • 2017-06-21
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多