diet-ng icon indicating copy to clipboard operation
diet-ng copied to clipboard

Inlined templates usage

Open crimaniak opened this issue 7 years ago • 0 comments

This issue to share my experience of compileHTMLDietFileString() usage for diet templates embedded to code. There are two problems: file name required and incorrect line number when error is found. To fix it I created inlineDiet.d:

module inlineDiet;

struct InlineDiet
{
	string file;
	int line;
	string tpl;
}

template diet(string tpl, string file=__FILE__, int line=__LINE__)
{
	enum diet = InlineDiet(file, line, tpl);
}

template compileInline(InlineDiet tpl, ARGS...)
{
	import std.array : replicate;
	import diet.html;
	
	enum string file = tpl.file~"t";
	enum string eTpl = ("\n".replicate(tpl.line-1)~tpl.tpl);
	
	alias compileInline = compileHTMLDietFileString!(file, eTpl, ARGS);
}

I add "t" to the end of current file so if template included from some component.d it will be visible to diet-ng library as component.dt file. To fix line number template is prepended by required amount of new line symbols (requirement for correct work: opening quote of template string must be on the same line as diet() template call). So now I can create simple 1-file components like this:

class ManagerMainPage : BasicManagerPage
{
// ...

// controller

	override void doContent()
	{
		client = engine.clients[registrator.getLoggedUser().clientId];
		auto page = this;
		auto stats = getStats();
		
		output.compileInline!(tpl, page, stats);
	}
	
// view
	
	enum tpl = diet!`
extends manager/page

block content
	h2 Manager page
	table
		tr
			td Organization: 
			td #{page.client.name}
		tr
			td Users:
			td #{stats["users"]}
		tr
			td Sites:
			td #{stats["sites"]}
		tr
			td Devices:
			td #{stats["devices"]}
`;	
}

I think it will be useful to add something like inlineDiet.d to library (or modify compileHTMLDietFileString to fix these issues) because every who will use compileHTMLDietFileString() will face same problems.

crimaniak avatar Mar 10 '17 13:03 crimaniak