Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jade template engine, how to use layout.jade?

I have a website in node.js; to create a page, say mypage I noticed I need to create both a layout.jade and mypage.jade files. If I put code in mypage.jade it is not displayed, so first I have to fill layout.jade with the layout of the page.

My question is, how do I reference inside layout.jade that I would like to load the content of mypage.jade in a certain container, for example? Can I have different pages with the same layout? How can I do this?

Thanks

like image 759
Masiar Avatar asked Dec 06 '11 15:12

Masiar


People also ask

How do you set Jade as view engine?

Now, write the following code to render above Jade template using Express. js. var express = require('express'); var app = express(); //set view engine app. set("view engine","jade") app.

What is Jade templating?

Jade is a template engine for node. js and the default rendering engine for the Express web framework. It is a new, simplified language that compiles into HTML and is extremely useful for web developers. Jade is designed primarily for server-side templating in node.

How do you run Jade?

All jade files need to be transformed in the HTML. Also don't forget that you need to install other dependencie like express, nodemailer, etc (see requires in the source code). And the application should by available on http://localhost/3000. All Jade templates will be correctly rendered and displayed as HTML.


2 Answers

http://expressjs.com/guide.html#view-rendering

If you don't want to use layouts you can disable them globally:

app.set('view options', {
  layout: false
});

If you don't do that layouts are enabled by default and Express searches for the standard layout in your_view_folder/layout.jade

You can specify a separate layout for each route though:

res.render('page', { layout: 'mylayout.jade' }); 
// you can omit .jade if you set the view engine to jade

Here's how your layout file could be:

doctype html
html(lang="en")
  head
    title Testing 123
  body
    div!= body

Note that body will be taken from "mypage.jade".

Edit:

Here's a real example in an application:

The application file (containing routes and configs):
https://github.com/alexyoung/nodepad/blob/master/app.js

The layout file:
https://github.com/alexyoung/nodepad/blob/master/views/layout.jade

like image 155
alessioalex Avatar answered Oct 22 '22 18:10

alessioalex


A little late to the party but I struggled to find the answer initially... In layout.jade

doctype html
html(lang="en")
    head
    body
        h1 Hello World
        block myblock

Then in index.jade

extends layout
    block myblock
        p Jade is cool

Will render

<!DOCTYPE html>
<html lang="en">
<head>
<body>
    <h1>Hello World</h1>
    <p>Jade is cool</p>
</body>
</html>
like image 23
Scott Rickman Avatar answered Oct 22 '22 17:10

Scott Rickman