jade: if statements and nesting

随声附和 提交于 2020-01-01 01:41:06

问题


Concider this pseudo-ish server side code

if(isFixed) {
  <div class="fixed">
} else {
  <div>
}
    <p>Inner element</p>
  </div>

I try to do this in jade but...

 - if(mode === 'fixed') {
   div#tabbar
 - }
     p ...I cannot get this to be an inner element :(

It always renders like this, with the </div> closed:

<div id="tabbar"></div><p>I want this inside of the div</p>

Am I messing up the indention? Thanks!


回答1:


You need to separate control flow from the template. Try this:

divClass = null

if isFixed
   divClass = "fixed"

div(class=divClass)
   p inner element

Which in turn might suggest factoring out the "isFixed" parameter into the actual divClass parameter to be passed on. But that depends on your remaining code/template of course.


As an alternative, try a mixin:

mixin content
  p inner element

if (isFixed)
  div(class="test")
    mixin content
else
  div(class="other")
    mixin content



回答2:


I would approach this with a ternary (or fully written out conditional or method) to determine the class attribute. That allows you to keep the div on one line and keeps indentation like it would be for any other element:

div(class="#{ isFixed ? 'fixed' : '' }")
    p Inner Element



回答3:


Jade doesn't seem to have a built in solution to start and end the tags other than utilizing the 'pipe' character to render plain text.

- if(mode === 'fixed') {
| <div id="tabbar">
- }
| <p>I cannot get this to be an inner element :(</p>
- if(mode === 'fixed') {
| </div>
- }

Less cluttered solution -

div(class=(isFixed) ? 'fixed' : '')
  p inner element


来源:https://stackoverflow.com/questions/14415448/jade-if-statements-and-nesting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!