Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to ucfirst in a Jade template?

Tags:

node.js

pug

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 capitalize a variable is ugly, is there any way in Jade that I can define a custom function that I have available in every template like:

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

Thanks in advance!

like image 434
Sergi Ramón Avatar asked Feb 12 '13 15:02

Sergi Ramón


2 Answers

The contents of #{} are executed as standard JS, so you can pass in helper functions for use with things like that. You haven't specified, but assuming you are using Jade along with Express, you can do something like this:

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

That will expose a function called ucfirst within the Jade template. You could also pass it in as part of locals every time you render, but if you are using Express it will do it automatically.

like image 187
loganfsmyth Avatar answered Oct 31 '22 18:10

loganfsmyth


If you're willing to resort to CSS, you can create a class that capitalizes the first letter of every word within the target element.

CSS

.caps {
    text-transform: capitalize;
}

Jade

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

Resulting HTML

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

Resulting view

One Two Three
like image 39
Walter Roman Avatar answered Oct 31 '22 19:10

Walter Roman