【问题标题】:Hogan.js - reference an item with a specific indexHogan.js - 引用具有特定索引的项目
【发布时间】:2013-11-20 18:07:53
【问题描述】:

我希望只有一个部分用于数组中的特定项目。例如:

var items = ['first','second']

例如:

{{#items[1]}}
   Slightly different styling for the second item, for no difference other than it's the second item.
{{/items[1]}}

我试过了:

{{#items.1}}
  Slightly different styling for the second item, for no difference other than it's the second item.
{{/items.1}}

还有:

{{#items}}
  {{#0}}
     Slightly different styling for the second item, for no difference other than it's the second item.
  {{/0}}
{{/items}}

但这些都不起作用。

我真的不想制作像这样的对象:

{'1':'first','2':'second'}

因为那太恶心了。

有什么想法吗?

【问题讨论】:

    标签: javascript mustache hogan.js


    【解决方案1】:

    在我给你一些建议/解决方法之前 就像您说的那样,它只是一些愚蠢的样式,因此与渲染或数据无关。如果它在这个意义上有意义,您应该将其添加到您的数据中,以便更好地表示 ts 结构。

    Mustache 是一种无逻辑的模板语言,如果您觉得需要 Mustache 语言,则应尽可能保持其无逻辑,否则只需使用 Handlebars

    css

    你可以使用 css 为了那个原因; altho not in IE<9 注意过滤器中缺少“n”

    .selector:nth-child(2) {
        some: styling;
    }
    

    更改数据

    其次,您可以在将数据传递给 Hogan 之前对其进行更改 要么作为控制器中数据处理的一部分,要么作为 js 框架有时称它们为视图控制器, 把它变成一个对象就像你说的不是最好的方法,你可以把它变成一个数组的数组

    [ [1,'first'], [2, 'second'] ]

    车把

    如果您不需要 Hogan,Handlebars 有一个 {{@index}} 用于当前索引

    功能

    作为更改输入数据的替代方法,您可以创建一个辅助函数来为您处理该逻辑,但这又不是真正的逻辑,它只是可视化的。而且 mustache 是一种无逻辑的模板语言,所以在开始使用这些类型时要小心

    var items = ['first','second'];
    var data = {items:items};
    
    data.second= (function () {
        var i=0;
        return function () {
            return i++ === 1; //index 1 being the second item in an array
        }
    }());
    

    然后使用第二个助手

    {{#items}}
        {{#second}}
        Slightly different styling for the second item, for no difference other than it's the second item.
        {{/second}}
    {{/items}}
    

    【讨论】:

    • 感谢您的全面回答!我改用 express3-handlebars,它为我提供了与 hogan 相同的功能,因为它是一个插入式替代品。
    • 尝试了一下,我实际上意识到 Handlebars 不是一个解决方案:{{@index}} 仅用于循环,我不想看,只是字面上只有一个部分用于项目2.
    • @nailer 我刚刚意识到您可能意味着您只想要列表中的第二项 jsfiddle.net/LBNb8 但不是很灵活,只需在模板之外解决它
    • 谢谢。有没有办法创建一个带参数的助手?我不想为每个索引创建一个新的助手。
    • @nailer 确定 jsfiddle.net/3X78P 但是,为什么不只是循环;如果您不担心性能,循环很可能更快,编译模板是大部分工作
    猜你喜欢
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多