Giter Club home page Giter Club logo

koa-pug's Introduction

Koa-pug

Node version NPM version Dependency Status Travis CI

A Pug middleware for Koa.

Support Pug@3.

How to use

npm install koa-pug --save
const Koa = require('koa')
const path = require('path')
const Pug = require('koa-pug')

const app = new Koa()
const pug = new Pug({
  viewPath: path.resolve(__dirname, './views'),
  locals: { /* variables and helpers */ },
  basedir: 'path/for/pug/extends',
  helperPath: [
    'path/to/pug/helpers',
    { random: 'path/to/lib/random.js' },
    { _: require('lodash') }
  ],
  app: app // Binding `ctx.render()`, equals to pug.use(app)
})

pug.locals.someKey = 'some value'

app.use(async ctx => {
  await ctx.render('index', locals, true)
})

For koa@1:

const koa = require('koa')
const Pug = require('koa-pug')

const app = koa()
const pug = new Pug({ app: app })

app.use(function * () {
  yield this.render('index', locals, true)
})

Use koa-pug as a standalone Pug renderer:

const pug = new Pug({
  viewPath: path.resolve(__dirname, './views'),
  locals: { /* variables and helpers */ },
  basedir: 'path/for/pug/extends',
  helperPath: [
    'path/to/pug/helpers',
    { random: 'path/to/lib/random.js' },
    { _: require('lodash') }
  ],
  // Can work with / without Koa
  // app: app
})

async function sendEmail(recipients, tplFile, locals) {
  const body = await pug.render(tplFile, locals)
  await send(recipients, body)
}

Options

options are extended from Pug's options, all options will be passed to Pug compiler except the following:

viewPath: string: the location of Pug templates. Default is process.cwd().

locals: { [key: string]: any }: variables and helpers that will be passed to Pug compiler.

helperPath: string | string[] | { [key string]: string }: location(s) of helper(s).

Content-Type

koa-pug will set content-type to text/html for you, you can change it:

await ctx.render('index')
ctx.type = 'text/plain'

Global Helpers

By setting helperPath, koa-pug will load all the modules that under sepecified folxder, and make them available on all templates.

helperPath also could be an array including folders, files path, even moduleName: 'path/to/lib.js mapping object. Also support node module as a helper, just like: '_': require('lodash')

Defining a Helper

// format-date.js, `koa-pug` will convert filename to camel case and use it as module name
module.exports = function (input) {
  return (input.getMonth() + 1) + '/' + input.getDate() + '/' + input.getFullYear()
}

Equals to:

// Becasue of there is a `moduleName`, `koa-pug` will use it as module name instead of filename
module.exports = {
  moduleName: 'formatDate',
  moduleBody (input) {
    return (input.getMonth() + 1) + '/' + input.getDate() + '/' + input.getFullYear()
  }
}

Use help in Pug:

p= formatDate(new Date())

How koa-pug resolves Pug template files

Let's say the project views structure like:

views
├── user.pug
├── user
│   └── index.pug
└── file
    └── index.pug

koa-pug will search file in the following order:

  • <tpl_name>.pug
  • <tpl_name>/index.pug

When pug.render('user') is called, views/user.pug will be rendered. If you want to render views/user/index.pug, you have to pass it to renderer explicitly: pug.render('user/index).

When pug.render('file') is called, views/file/index.pug will be rendered.

Contributors

Via GitHub

koa-pug's People

Contributors

chrisyip avatar dependabot[bot] avatar hanjukim avatar jaeh avatar jrvidal avatar lukeramsden avatar mull avatar pjincz avatar ryota-ka avatar superboum avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

koa-pug's Issues

this.render is not a function

I'm using koa@2 and getting _this.render is not a function

this.render('index')

Doing ctx.render does work but I need to specify 'index.pug' and not just 'index'. Also, not if it is related but string interpolation no longer works.

p.text-xs-center $ #{product.price}

Just outputs #{product.price} after it's converted to html.

package.json
{
  "koa": "^2.0.0",
  "koa-pug": "^3.0.0-0"
}

koa-pug

Now that Jade is naming itself pug do you have any plans to rename this repo to pug?

Exposing locals to layout

I'm having issues sending a local variable from a pug file to it's layout file. I'm not sure if this is an issue in koa-pug or in pug but I'll start here.

Working Example

layout.pug

block vars
p #{foo}

file.pug

extends layout.pug
block vars
  - var foo = 'bar'

This will print <p>bar</p>

Not working Example

layout.pug

block vars
p #{foo}

file.pug

extends layout.pug
block vars
  - var foo = baz

controller.js

await ctx.render('file', {baz: 'bar'});

This will print <p></p>

Outdated dependencies

Dependencies used in the project are outdated:

"dependencies": {
-    "fs-extra": "^0.24.0",
-    "lodash": "^3.10.1",
-    "pug": "^2.0.0-alpha6"
+    "fs-extra": "^0.30.0",
+    "lodash": "^4.16.4",
+    "pug": "^2.0.0-beta6"
   },
   "devDependencies": {
-    "bluebird": "^2.9.34",
+    "bluebird": "^3.4.6",
     "chai": "^3.2.0",
-    "cheerio": "^0.19.0",
-    "eslint": "^1.10.2",
-    "istanbul": "^0.3.19",
-    "jstransformer-markdown-it": "^0.1.0",
+    "cheerio": "^0.22.0",
+    "eslint": "^3.7.1",
+    "istanbul": "^0.4.5",
+    "jstransformer-markdown-it": "^1.0.0",
     "koa": "^1.0.0",
     "koa-route": "^2.4.2",
     "koa-vhost": "^0.5.0",
     "marked": "^0.3.5",
-    "mocha": "^2.3.0",
-    "supertest": "^1.1.0",
-    "supertest-koa-agent": "^0.2.1"
+    "mocha": "^3.1.0",
+    "supertest": "^2.0.0",
+    "supertest-koa-agent": "^0.3.0"
   },

However, updating all the dependencies makes it incompatible with older releases of node.js(before 4).

Also, is it a good idea to have pug as a dependency? There could be different versions being used by the project and koa-pug.

Maximum call stack size exceeded

Hi,

I keep getting this error when I call this.render using koa-jade:


server error [RangeError: Maximum call stack size exceeded] { request:
{ method: 'GET',
url: '/daniel',
header:
{ 'x-real-ip': '10.211.55.2',
'x-forwarded-for': '10.211.55.2',
host: 'docs.sandbox.local:80',
'x-nginx-proxy': 'true',
connection: 'close',
'cache-control': 'max-age=0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36',
'accept-encoding': 'gzip, deflate, sdch',
'accept-language': 'en-US,en;q=0.8',
cookie: '_ga=GA1.2.1728672733.1439768627' } },
response:
{ status: 200,
message: 'OK',
header:
{ 'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET,HEAD,PUT,POST,DELETE',
'cache-control': 'no-cache',
'content-type': 'text/html; charset=utf-8',
'content-length': '19' } },
app: { subdomainOffset: 2, env: 'development' },
originalUrl: '/daniel',
req: '',
res: '',
socket: '' }


This is the code:

'use strict';
'use esnext';

function *base(route, next) {
yield this.render('base', {
title: 'Docs',
styles: [
// materialize
'/materialize.min.css',

        // material icons
        '/css/materialdesignicons.min.css',

        // graphkit
        '/app.css'
    ],
    vendors: [
        // jquery
        '/jquery.min.js',

        // angular
        '/angular.min.js',
        '/angular-aria.min.js',
        '/angular-route.min.js',

        // materialize
        '/materialize.min.js',

        // d3
        '/d3.min.js'
    ],
    packages: [
        // app
        '/app.js',
        '/auth.js',
        '/connect.js',
        '/http.js',
        '/router.js'
    ]
}, true);

if (undefined !== next) {
    yield next;
}

}

function *index(route, next) {
yield this.render('routes/index', {}, true);
}

function *profile(route, next) {
yield this.render('routes/profile', {}, true);
}

function *error(route, next) {
yield this.render('routes/error404', {}, true);
}

module.exports = function(app) {
const koaRoute = require('koa-route');
const koaJade = require('koa-jade');
const jade = new koaJade({
viewPath: __dirname + '/src/views',
debug: 'development' == app.env,
pretty: 'development' == app.env,
compileDebug: 'development' == app.env,
locals: {
title: 'Docs'
},
basedir: '/',
noCache: true,
helperPath: [
//'path/to/jade/helpers',
//{ random: 'path/to/lib.js' },
]
});

app.use(jade.middleware);

// base
app.use(koaRoute.get('/', base));
app.use(koaRoute.get('/a/welcome', base));
app.use(koaRoute.get('/:username', base));

// index
app.use(koaRoute.get('/route/index', index));

// profile
app.use(koaRoute.get('/route/profile', profile));

};

Can Koa-pug render multiple blocks?

//layout.pug
html
    head
        body
            block navbar
            block content

Navbar (navbar.pug, navbarAuth.pug)
Content (index.pug, signin.pug, signup.pug)

When I use ctx.render("index"), it render just index.pug only.

//index.pug
extends layout
    block navbar
    block content

Why does `BaseContext.render` have to return `void` ?

I am trying to use [email protected] with TypeScript@^3.2
Please tell me the reason why the return type of BaseContext.render is not Promise<void> but void ? Due to the declaration merging at here,

declare module 'koa' {
  export interface BaseContext {
    render: (tpl: string, locals?: any, options?: RenderOptions, noCache?: boolean) => void
  }
}

I receive some lint violations from ESLint when I try to call render method of ctx.

ctx.status = 404;
await ctx.render('4xx.pug');

error Unexpected await of a non-Promise (non-"Thenable") value @typescript-eslint/await-thenable`

If the view provided is a folder, pick index.jade as default

Hi

If the view folder structure looks like this

- views
 |--- home
    |--- index.jade

In express you can do the following

res.render('home');

But with koa-jade, it looks for home.jade. Maybe, if the path provided is a directory, try to find index.jade first, and then throw an error if that one does not exist.

If I find the time, I will create a pull request for this

Please upgrade lodash

koa-pug is based on lodash.forin (as well as other lodash extracts) made with version 4.4.0 and is subject to many vulnerabilities (see lodash/lodash#5808).

Is there a chance you could use the latest version of lodash (4.17.21) instead ?

'pretty: true' not working

I have the following jade object:

var Jade = require('koa-jade');

var jade = new Jade({
  viewPath: Path.join(__dirname, '..', 'app', 'templates'),
  pretty: true,
  basedir: Path.join(__dirname, '..', 'app', 'templates')
});

app.use(jade.middleware);

My templates are showing up correctly but they are not using Jade's pretty print option.

<!DOCTYPE html><html><head><title>Testing</title></head><body><h1>This is a test</h1><p>Hello World!</p></body></html>

TypeScript error on koa import

When running tsc I get the following error:

Screen Shot 2019-12-16 at 11 31 52 AM

If I update the import statement in the referenced dist file (koa-pug/dist/index.d.ts) to import * as Koa from 'koa' the error goes away.

I'm using the following package versions:

  • koa-pug: 4.0.2
  • koa: 2.11.0
  • @types/koa: 2.11.0

import Koa from 'koa'

I don't know much about Typescript, but if you were able to update your import signature for Koa, I assume that would fix this issue for me and for anyone else who might have it. Also open to a different solution for resolving this issue!

Let me know if there are any further details I can provide.

Thanks!

jade extends basedir functionality not working with absolute paths

ok I reviewed the example app in your repo and it works, however my apps view structure is a little different as my jade file is not above the layout jade file in the directory structure:
/views/
/layouts/layout.jade
/main/index.jade

so in index.jade the first line is extends /layouts/layout but when trying to render I get the following error:
the "basedir" option is required to use "extends" with "absolute" paths

in express this used to be handled with app.locals.basedir = same as view path; but I'm having trouble figuring out how to do it with this plugin.

I tried setting the basedir in the middleware locals option to no avail like so:
app.use(jade.middleware({
viewPath: __dirname + '/views',
debug: false,
pretty: false,
compileDebug: false,
locals: {basedir: __dirname + '/views'},
// helperPath: [
// 'path/to/jade/helpers',
// { random: 'path/to/lib.js' },
// { _: require('lodash') }
// ]
}));

everything is configured properly because if I change the first line of index.jade to "extends ../layouts/layout" everything renders as expected; but believe this is bad form.

is this scenario supposed to be supported or should I try using something like koa-locals?

Map is not defined

Just installed Koa-Jade and I'm getting this error:

, compilers = new Map()
                  ^
ReferenceError: Map is not defined
    at new Jade (/node_modules/koa-jade/index.js:74:23)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.