Jade Templates - Dynamic Attributes

Rafael Motta picture Rafael Motta · Nov 27, 2012 · Viewed 12.8k times · Source

I want to create attributes on the fly for some html elements.

In my case I'd like to set (or not) a disabled attribute according to user.role.

So, if user has permission to edit some field, I do not want to put disabled attribute on the element. Otherwise, I do want it.

I know that I can do this with these approaches:

- Approach 1 - Use Conditionals

if (user.role === 1)
   input(type='text', name='foo')
else
   input(type='text', name='foo', disabled)

- Approach 2 - Plain HTML

- var disabledAttr = (user.role === 1) ? "disabled" : "";
| <input type="text" name="foo" #{ disabledAttr} />

Approach 1 is bad because I need to repeat some code. With Approach 2 I do not need to repeat code but I have to use plain HTML instead of Jade markup.

I tried something like this:

input(type='text', name='foo', #{ disabledAttr} )

But jade generates the following code:

<input type="text" name="foo" disabledattr="" />

Any better idea?

Answer

saintedlama picture saintedlama · Nov 28, 2012

Jade is quite clever when it needs to figure out how to render attributes. You can render your disabled attribute using this single line of jade markup

input(type='text', name='foo', disabled=role!==1)