Search code examples
pugtemplatingejs

Convert Jade to EJS


Can anyone please help by convert this Jade to EJS?

extends layout

block content
    h1.
        User List
    ul
        each user, i in userlist
            li
                a(href="mailto:#{user.email}")= user.username

Solution

  • There is no block but an include logic available in EJS. Split up the "main layout" that way that you can include a header and footer (or whatever suits your needs). The iteration is expressed in plain JavaScript escaped in sequences of <% ... %>. Using <%= ... %> directly outputs the referenced var. Your resulting EJS code might look as follows:

    <h1>User List</h1>
    <ul>
        <% for (var i = 0; i < user.length; i++) { %>
            <li><a href="mailto:<%= user[i].email %>"><%= user[i].username %></a></li>
        <% } %>
    </ul>
    

    or, alternatively:

    <h1>User List</h1>
    <ul>
        <% user.forEach(function(user) { %>
            <li><a href="mailto:<%= user.email %>"><%= user.username %></a></li>
        <% )} %>
    </ul>
    

    The include syntax is straight forward:

    <% include partials/header %>
    ...
    <% include partials/footer %>
    

    Note: Include files are located relative to the template with the include statement. Extensions are added automatically. So if your template is stored in let's say /views, the full path for the header include would be /views/partials/header.ejs.