Moritz Pfeiffer Moritz Pfeiffer - 3 months ago 20
Node.js Question

jade/pug seperate control flow from templating

Isn't it possible to seperate control flow from template? I want to check a few variables if they are null or undefined and in case want to initialize with an empty string. tried like this:

meta(property="og:site_name", content=pageData.name)
meta(property="og:title", content=pageData.name)
- var article_id = pageData.article_id
- var ean = pageData.ean
- var color = pageData.color

if article_id == null
article_id = ""
if ean == null
ean = ""
if color == null
color = ""

- var description = pageData.name + " " + article_id + " " + ean + " " + color
meta(name='description', content=description)
meta(property="og:description", content=description)


but the last two meta tags will never appear. i assume pug is going into an if and never comes back? but i cant create a control flow for every null variable this would get crazy unclear.

Answer

this will fix it (adding - before setting js variables.

meta(property="og:site_name", content=pageData.name)
meta(property="og:title", content=pageData.name)
- var article_id = pageData.article_id
- var ean = pageData.ean
- var color = pageData.color

if article_id == null
  - article_id = ""
if ean == null
  - ean = ""
if color == null
  - color = ""

- var description = pageData.name + " " + article_id + " " + ean + " " + color
meta(name='description', content=description)
meta(property="og:description", content=description)

as of separation, if youre using express for example, when you call res.render you can send js functions and variables to be sent to the view and used there.

res.render('email', {
  pageData: pageData,
  articleId : pageData.article_id || ""
});