Use a variable in a Jade include

前端 未结 5 1980
暖寄归人
暖寄归人 2020-11-27 14:22

I\'m working with Jade and Express and I would like to use a variable in my include statement. For example:

app.js

app.get(\'/admin\', function (req,         


        
5条回答
  •  执笔经年
    2020-11-27 15:17

    Found this page googling for the same question, but in a different context, so thought I'd put my solution (read: workaround) here for posterity:

    I wanted to surround my include with more context pulled from the variable, e.g. (simplified):

    - var templates = page + '/templates/'
    - var headid = page + 'head'
    - var imgsrc = '/images/' + page
    div(id=headid)    
      h1 #{page}
      img(src=imgsrc)
    div(id=page)
      include templates
    

    Since that doesn't work (Jade doesn't support dynamic includes, as noted by freakish), I hybridized with a mixin:

    (Edit– a little more elegant than my previous workaround:)

    mixin page1
      include page1/templates
    
    mixin page2
      include page2/templates
    
    ...
    
    - for (var i = 0; i < 3; i++)
      - var page = 'page' + i
      - var headid = page + 'head'
      - var imgsrc = '/images/' + page
      div(id=headid)    
        h1 #{page}
        img(src=imgsrc)
      div(id=page)
        +page
    

    My previous answer:

    mixin templates(page)
      - var headid = page + 'head'
      - var imgsrc = '/images/' + page
      div(id=headid)    
        h1 #{page}
        img(src=imgsrc)
    
    +templates('page1')
    #page1
      include page1/templates/
    
    +templates('page2')
    #page2
      include page2/templates/
    
    ...
    

    It's not elegant, and it won't work if you need to include more than a few things this way, but at least part of the Jade is dynamic.

提交回复
热议问题