Defining default values to vary with the Pug Engine Template

1

I'm starting to work with MEAN and use the Pug template engine. I know the same was Jade previously and there have been updates on how to work with it.

My problem is that in Jade, and in various places on the internet, I have the information that to set a default value for a variable that is passed, I can use a declaration like this:

Piece of the application code with the parameter to be passed

// ...
app.get('/',function(req, res){
    res.render('foo', {
        'bar':'hello ',
        //'bin': 'world!!!' // <-- variavel comentada de proprósito
    });
})

My foo.pug file

html
  head
    title= Testando
  body
    bar bin

The problem in question is that if bin is not sent, my foo.pug of the stick in the render saying that it did not find the variable. How do I set a default value if bin is not sent to my template?

    
asked by anonymous 20.01.2017 / 02:42

1 answer

1

I found some solutions that depend on the form of development in which it is being applied:

Solution 1: Using a if else conditioner to check whether or not the element exists:

html
  head
    title= Testando
body
  if (bar && bin)
    bar bin
  else if (bar && !bin)
    bar world!!!

This solution is interesting when you have to import a file or a mixed-code block between variables and content .

Solution 2: Using tenant operators for field validation:

html
  head
    title= Testando
body
  typeof bin == 'undefined' ? bar world!!! : bar bin

Working with tenant operators, you will always have a callback for that parameter .

Solution 3: declare these variables with the Unbuffered Code :

- var bin = bin || 'world!!!';
- var bar = bar || 'hello ';
html
  head
    title= Testando
body
    bar bin

I noticed that I can change the value of the variables depending on the file to be imported, that is, if there is a new declaration - var bin = bin || 'foo!!!'; * I can change the default value of the content that should be displayed or of the expression bin will be declared as * - var bin = '123' .

Solution 4: declare these variables with the Buffered Code a> :

html
  head
    title= Testando
body= (bar || 'hello ') + (bin || 'world!!!')

This solution is an implementation of Solution 2 without variant declaration. The Pug understands that content of the type document.body.innerHTML (which is the tag in question) will be populated with the result of the expression.

Solution 5: Declare these variables with the Unescaped Buffered Code :

html
  head
    title= Testando
body
  != (bar || 'hello ') + (bin || 'world!!!')

This solution, which I see as more satisfying, allows that anywhere, regardless of whether I am inside a block of content, I can insert a complete expression, so I do not depend on a .

    
20.01.2017 / 12:14