Handlebars templates for Koa
Check out these outstanding ES6 courses by @wesbos
koa-hbs is middleware. We stash an instance of koa-hbs for you in the libraryso you don't have to manage it separately. Configure the default instance bypassing an options hash to #middleware. To render a template then,just yield this.render('templateName');
. Here's a basic app demonstrating all that:
var koa = require('koa');
var hbs = require('koa-hbs');
var app = koa();
// koa-hbs is middleware. `use` it before you want to render a view
app.use(hbs.middleware({
viewPath: __dirname + '/views'
}));
// Render is attached to the koa context. Call `this.render` in your middleware
// to attach rendered html to the koa response body.
app.use(function *() {
yield this.render('main', {title: 'koa-hbs'});
})
app.listen(3000);
After a template has been rendered, the template function is cached. #render
accepts two arguments - the template to render, and an object containing localvariables to be inserted into the template. The result is assigned to Koa'sthis.response.body
.
The plan for koa-hbs is to offer identical functionality as express-hbs(eventaully). These options are supported now.
viewPath
requiredType: Array|String
Full path from which to load templates
handlebars
Type:Object:Handlebars
Pass your own instance of handlebars
templateOptions
Type: Object
Hash of handlebars options topass to template()
extname
Type:String
Alter the default template extension (default: '.hbs'
)
partialsPath
Type:Array|String
Full path to partials directory
defaultLayout
Type:String
Name of the default layout
layoutsPath
Type:String
Full path to layouts directory
contentHelperName
Type:String
Alter contentFor
helper name
blockHelperName
Type:String
Alter block
helper name
disableCache
Type:Boolean
Disable template caching
Helpers are registered using the #registerHelper method. Here is an exampleusing the default instance (helper stolen from official Handlebarsdocs:
hbs = require('koa-hbs');
hbs.registerHelper('link', function(text, url) {
text = hbs.Utils.escapeExpression(text);
url = hbs.Utils.escapeExpression(url);
var result = '<a href="' + url + '">' + text + '</a>';
return new hbs.SafeString(result);
});
Your helper is then accessible in all views by using, {{link "Google" "http://google.com"}}
The registerHelper
, Utils
, and SafeString
methods all proxy to aninternal Handlebars instance. If passing an alternative instance ofHandlebars to the middleware configurator, make sure to do so beforeregistering helpers via the koa-hbs proxy of the above functions, orjust register your helpers directly via your Handlebars instance.
You can also access the current Koa context in your helper. If you want to havea helper that outputs the current URL, you could write a helper like the followingand call it in any template as {{requestURL}}
.
hbs.registerHelper('requestURL', function() {
var url = hbs.templateOptions.data.koa.request.url;
return url;
});
The simple way to register partials is to stick them all in a directory, andpass the partialsPath
option when generating the middleware. Say your viewsare in ./views
, and your partials are in ./views/partials
. Configuring themiddleware via
app.use(hbs.middleware({
viewPath: __dirname + '/views',
partialsPath: __dirname + '/views/partials'
}));
will cause them to be automatically registered. Alternatively, you may registerpartials one at a time by calling hbs.registerPartial
which proxies to thecached handlebars #registerPartial
method.
Passing defaultLayout
with the a layout name will cause all templates to beinserted into the {{{body}}}
expression of the layout. This might look likethe following.
<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
</head>
<body>
{{{body}}}
</body>
</html>
In addition to, or alternatively, you may specify a layout to render a templateinto. Simply specify {{!< layoutName }}
somewhere in your template. koa-hbswill load your layout from layoutsPath
if defined, or from viewPath
otherwise. If viewPath
is set to an Array of paths, the first path in thearray will be assumed to contain the layout named.
At this time, only a single content block ({{{body}}}
) is supported.
As of version 0.9.0, it's possible to override the layout used for rendering,using locals
. For example:
router.get('/', function *() {
yield this.render('foo', {
layout: 'bar'
});
});
See the testsfor more.
Reserve areas in a layout by using the block
helper like so.
{{#block "sidebar"}}
<!-- default content for the sidebar block -->
{{/block}}
Then in a template, use the contentFor
helper to render content into theblock.
{{#contentFor "sidebar"}}
<aside>
<h2>{{sidebarTitleLocal}}</h2>
<p>{{sidebarContentLocal}}</p>
</aside>
{{/contentFor}}
To disable the caching of templates and partials, use the disableCache
option.Set this option to true
to disable caching. Default is false
.Remember to set this option to false
for production environments, or performancecould be impacted!
Application local variables ([this.state](https://github.com/koajs/koa/blob/master/docs/api/context.md#ctxstate)
) are provided to all templates rendered within the application.
app.use(function *(next) {
this.state.title = 'My App';
this.state.email = 'me@myapp.com';
yield next;
});
The state object is a JavaScript Object. The properties added to it will beexposed as local variables within your views.
<title>{{title}}</title>
<p>Contact : {{email}}</p>
Koa2 is supported via the @next
module version. It is considered experimentaland requires Node v7 or higher. You can obtain this version by running:
npm install koa-hbs@next --save
For information on using this version, please read the branch'sREADME. If using a version ofnode older than v7.6, we recommend usingharmonica to enable the --harmony
flags, which activates native async/await
support.
If you'd rather not use an experimental version, or you need to use an olderversion of Node, you can reference this examplerepo that demonstrates how to use koa-hbs
with Koa2:koa-hbs-koa2-howto
Credit to @chrisveness for the initial investigation.
You can run the included example via npm install koa
andnode --harmony app.js
from the example folder.
Here's a few things koa-hbs does not plan to support unless someone canprovide really compelling justification.
koa-hbs does not support asynchronous helpers. No, really - just load yourdata before rendering a view. This helps on performance and separation ofconcerns in your app.
As of koa-hbs@0.9.0, the version of the Handlebars dependency bundled with thismodule has been updated to 4.0.x. If this causes conflicts for your project, youmay pass your own instance of Handlebars to the module, or downgrade to the last0.8.x version.
Functionality and code were inspired/taken fromexpress-hbs.Many thanks to @jwilm for authoring this middleware.
一.简介 koa2是基于 Node.js 平台的下一代 web 开发框架, 致力于成为一个更小、更富有表现力、更健壮的 Web 框架。 可以避免异步嵌套. express中间件是异步回调,Koa2原生支持async/await 二.async/await const { rejects } = require("assert"); const { resolve } = require("path
个人比较喜欢handlebars渲染,不喜欢ejs、jade之类,因此在试验koa2开发时,第一时间就想到集成koa-hbs模块! koa-hbs模块来自https://github.com/gilt/koa-hbs 问题是,该模块不支持koa2,就支持koa1 那么咱就出动koa-convert模块来进行转换……可是,仍然有问题。关键点在于ctx.render方法仍然是个generator函数。
配置简单路由 引入中间件 配置需要的路由 通过app.use注册路由 const Koa = require('koa') const app = new Koa() // 引入koa-router并对其实例化 const router = require('koa-router')() // 配置get路由 router.get('/get', function (ctx, next) {
下载依赖: yarn add koa@2.0.0 yarn add koa-router@7.0.0 //路由匹配 yarn add koa-bodyparser // 处理post请求 基本使用: const Koa = require('koa'); const app = new Koa(); app.use(async (ctx, next) => { ctx.body =
版本4.1.1 惯例,先来看看简单的使用 const Koa = require('koa'); const body = require('koa-body'); const app = new Koa(); // 可以给parsedMethods传想要koa-body解析的方法 app.use(body({parsedMethods: ['POST', 'PUT', 'PATCH', 'G
项目博客 log4js日志的使用与详解 记录下,待code尝试
Koa art-template view render middleware. support all feature of art-template. Install npm install --save art-template npm install --save koa-art-template Example const Koa = require('koa'); const ren
koa是Express的下一代基于Node.js的web框架,目前有1.x和2.0两个版本。 历史 1. Express Express是第一代最流行的web框架,它对Node.js的http进行了封装,用起来如下: var express = require('express'); var app = express(); app.get('/', function (req, res) {
Koa 是下一代的 Node.js 的 Web 框架。由 Express 团队设计。旨在提供一个更小型、更富有表现力、更可靠的 Web 应用和 API 的开发基础。 Koa可以通过生成器摆脱回调,极大地改进错误处理。Koa核心不绑定任何中间件,但提供了优雅的一组可以快速和愉悦地编写服务器应用的方法。 示例代码: var koa = require('koa');var app = koa();//
Koa - HelloWorld 以上便是全部了,我们重点来看示例,我们只注册一个中间件, Hello Worler Server: <?php $app = new Application(); // ... $app->υse(function(Context $ctx) { $ctx->status = 200; $ctx->body = "<h1>Hello Worl
koa-log4js A wrapper for log4js-node which support Koa logger middleware.Log message is forked from Express (Connect) logger file. Note This branch is use to Koa v2.x.To use Koa v0.x & v1.x, please ch
koa-rudy 环境 node -v >=6.9.0pm2 启动 npm install npm run dev 开发环境 npm run dev || test || prod 接口测试 npm run mocha 推荐开发工具 vscode 实现 支持 async/await MVC架构(middleware-view-controller) RESTful a
学习 koa 源码的整体架构,浅析koa洋葱模型原理和co原理 1. 前言 你好,我是若川,微信搜索「若川视野」关注我,专注前端技术分享。欢迎加我微信ruochuan12,加群交流学习。 这是学习源码整体架构系列第七篇。整体架构这词语好像有点大,姑且就算是源码整体结构吧,主要就是学习是代码整体结构,不深究其他不是主线的具体函数的实现。本篇文章学习的是实际仓库的代码。 本文仓库地址:git clon
koa-seo SEO middleware for koa base on chrome-render, a substitute for prerender. Modern web app use technique like react.js vue.js which render html in browser, this lead to search engine can't crawl