Is ucfirst best in a jade pattern?

Is there a better way to capitalize the first character of a string in Jade than this?

for list in project.lists - list.name = list.name.charAt(0).toUpperCase() + list.name.slice(1); li #{list.name} 

Doing this every time I want to use a variable is ugly, is there any way in Jade that I can define a user-defined function that I have in each template, for example:

 for list in project.lists li #{ucfirst(list.name)} 

Thanks in advance!

+6
source share
3 answers

The content #{} runs as standard JS, so you can pass helper functions for use with such things. You did not specify, but assuming that you are using Jade with Express, you can do something like this:

 app.locals.ucfirst = function(value){ return value.charAt(0).toUpperCase() + value.slice(1); }; 

A function named ucfirst will be exposed in the Jade template. You can also pass it as part of the locals with every render, but if you use Express, it will do it automatically.

+15
source

If you want to resort to CSS, you can create a class that captures the first letter of each word in the target element.

CSS

 .caps { text-transform: capitalize; } 

Jade

 div.caps each foo in ['one', 'two', 'three'] span #{foo} 

HTML result

 <div class="caps"><span>one</span><span>two</span><span>three</span> 

Resulting view

 One Two Three 
0
source

If you are using a pug with gulp, this might be useful:

 mixin ucfirst(text) - text = text.charAt(0).toUpperCase() + text.slice(1); . #{text} 

Just call it like any other mixin:

 li +ucfirst(list.name) 
0
source

All Articles