Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jade Templates - Dynamic Attributes

Tags:

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?

like image 702
Rafael Motta Avatar asked Nov 27 '12 20:11

Rafael Motta


3 Answers

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)
like image 169
saintedlama Avatar answered Sep 24 '22 07:09

saintedlama


You can to use a bunch of attributes in a conditional way:

input(type='text')&attributes(user.role === 1 ? {'disabled': 'true'} : {'class': 'admin', 'ng-model': 'vm.model.name', 'ng-click': 'vm.click()'})
like image 33
AA. Avatar answered Sep 25 '22 07:09

AA.


This syntax works for me:

input(placeholder!="<%= translate('Add new item') %>")

where translate is a function that returns translated text.

like image 29
sq2 Avatar answered Sep 24 '22 07:09

sq2