crash crash - 1 month ago 19
Node.js Question

Conditional class in Marko JS Template

I am using the

layout
taglib to extend a page to its template but i don't know how to pass a variable to the main layout and apply a conditional class.

Considering this is my
main-layout.marko


<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body class="#### (TITLE === 'REGISTER')?'ACTIVE':'INACTIVE' ####">
<layout-placeholder name="title"/>
<layout-placeholder name="body"/>
</body>
</html>


this is my
registration.marko


<layout-use template="./layout.marko">
<layout-put into="title">
$data.title
</layout-put>
<layout-put into="body">
some content
</layout-put>
</layout-use>


and finally this is the code I use to render the page and pass the title data

router.get('/register', function(req, res, next) {
registration.render({
title: 'register'
}, res);
});


How can I create a conditional class on the
main-layout.marko
file that switches between active or inactive depending on the page title?

Thanks

Answer

You can pass data to a layout by adding additional attributes to your <layout-use> tag. See: marko-layout ยป Layout Data

For your example, the following will work:

In main-layout.marko:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body class="#### ${data.title === 'REGISTER' ? 'ACTIVE' : 'INACTIVE' } ####">
    <layout-placeholder name="title">
      ${data.title}
    </layout-placeholder>
    <layout-placeholder name="body"/>
  </body>
</html>

In registration.marko:

<layout-use template="./layout.marko" title="${data.title}">
    <layout-put into="body">
      some content
    </layout-put>
</layout-use>

That should solve your problem, but let me know if you are still stuck.