Jade / Pug:如何在另一个mixin的参数数组中使用mixin

时间:2016-05-27 16:06:09

标签: node.js pug mixins

我正在尝试在Jade / Pug中使用原子设计模式来创建一个带有链接的简单列表。我的列表mixin如下,并接受一系列项目:

include ../../atoms/listitem/listitem
mixin list(spec)
    - spec = spec || {}
    - spec.__class = spec.__class || ''
    - spec.type = spec.type || 'ul'
    - spec.items = spec.items || {}

    if spec.items.length
        #{spec.type}
            for item in spec.items
                +listitem({content: item})

列出项目:

mixin listitem(spec)
    - spec = spec || {}
    - spec.__class = spec.__class || ''
    - spec.content = spec.content || ''

    li(class=spec.__class)&attributes(attributes)
        != spec.content

链接:

mixin link(spec)
    - spec = spec || {}
    - spec.__class = spec.__class || ''
    - spec.text = spec.text || 'Default Link'

    a.link(class=spec.__class)&attributes(attributes)
        if block
            block
        else
            != spec.text

在我的模板中,我有以下内容:

include _modules/atoms/link/link
include _modules/molecules/list/list

block content
    +list({items: [
        'list item 1',
        'list item 2',
        +link({text: "Hi link"})(href="#"),
        'list item 4'
    ]})

我收到了一个错误:

link is not a function

但是,如果我使用该项目数组之外的链接,它的工作正常。我做错了什么?

2 个答案:

答案 0 :(得分:2)

唉,你不能把Jade中的mixin作为另一个mixin的参数。如果要保留大部分格式:为了获得您想要的功能,您必须在多个实例中使用类型检测并将您的参数作为数组传递。

mixin listitem(spec)
    - spec = spec || {}
    - spec.__class = spec.__class || ''
    - spec.content = spec.content || ''

    li(class=spec.__class)&attributes(attributes)
       if (typeof spec.content === 'string') 
         != spec.content
       else
         block

mixin link(spec)
    - spec = spec || {}
    - spec.__class = spec.__class || ''
    - spec.text = spec.text || 'Default Link'
    - attributes = spec.attributes || ''


    a.link(class=spec.__class)&attributes(attributes)
        if block
            block
        else
            != spec.text


mixin list(spec)
    - spec = spec || {}
    - spec.__class = spec.__class || ''
    - spec.type = spec.type || 'ul'
    - spec.items = spec.items || {}

    if spec.items.length
        #{spec.type}
            for item in spec.items
               +listitem({content: item})
                 if (item[0])
                   +link(item[0])


block content
    +list({items: [
        'list item 1',
        'list item 2',
        [{text: "Hi link"}],
        'list item 4'
    ]})

答案 1 :(得分:0)

mixin不能是数组中的对象。考虑重新格式化您的对象并解决这样的问题(简化为沟通概念):

-
  var myList = [
    {text: 'list item 1'},
    {text: 'list item 2', link: '#'},
    {text: 'list item 3'}
  ];

mixin list(listObject)
  ul
    for each listItemObject in listObject
      +listItem(listItemObject)

mixin listItem(listItemObject)
  li
    if (listItemObject.link.length > 0)
      a(href= listItemObject.link)= listItemObject.text
    else
      #{listItemObject.text}