Skip to content

Instantly share code, notes, and snippets.

@Globik

Globik/markserver.js

Last active Dec 14, 2018
Embed
What would you like to do?
Local variables in Koa.js context with Marko.js templating engin. + fs.watch for marko/hot-reload. Version1.
//var chokidar=require('chokidar');=> alas, it will not work. Just I don't know how
var koa=require('koa');
var path=require('path');
var serve=require('koa-static');
var Router=require('koa-router');
var fs=require('fs');
var viewsDir=path.join(__dirname,'templates');
require('marko/node-require').install();
var marko=require('marko');
require('marko/hot-reload').enable();
require('fs').watch(viewsDir,function(event,pat){
console.log(event,pat);
if(/\.marko$/.test(pat)){
var templpath=path.join(viewsDir,pat);
require('marko/hot-reload').handleFileModified(templpath);//magic with actually reloading
}
});
function marki(app,settings){
if(app.context.stream){return;}
var settings=settings || {};
function *stream(view,ops){
console.log('viewPath :',view)
console.log
('ops :',ops) var temp=marko.load(require.resolve(`./templates/${view}`));
var fn=temp.stream(ops);
return fn;
}
app.context.stream=function *(view,_context){
var context = {};
//here is a magik with globals variables
merge(context, this.state);
merge(context, _context);
//I don't know is it correct for a stream yield * stream?
var html = yield *stream(view, context);
return html;
}
}
var app=koa();
app.use(serve(__dirname+'/public'));
//marko.js middleware. I don't know marko's settings :(
marki(app,{});
//here context.state middleware(this.state) for throu routes globally and on a template site
//in hello-world.marko => ${data.admin} => Bobik
app.use(function *(next){
this.state.admin="Bobik";
yield next;})
var router=new Router();
//var template=marko.load(require.resolve('./templates/hello-world.marko'));
router.get('/',function *(){
//var das=template.stream({name:"Jura",who:this.state.admin});
var das= yield this.stream('hello-world.marko',{name:"Bobik",who:"I am"})
this.type='html';
this.body=das;
});
app.use(router.routes());
console.log(3000);
app.listen(process.env.PORT || 3000);
function merge(target, source) {
for (var key in source) {
target[key] = source[key];
}
}
@Globik

This comment has been minimized.

Copy link
Owner Author

@Globik Globik commented Oct 28, 2015

this.state.admin is null, is nothing on includes and on a layout. Is it a bug? No idea.
There is the way. You should delegate global data via include, for example:
< include template="./main-menu.marko" menu="${data.admin}"/>
And in main-menu.marko => ${data.menu} => Bobik

@Globik

This comment has been minimized.

Copy link
Owner Author

@Globik Globik commented Jul 8, 2016

Before var html need to write try catch block.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment