vibe.d beta banner
get vibe.d

Asynchronous I/O that doesn’t get in your way, written in D

Function inject

Allows to pass additional variables to a function that renders a templated page.

auto auto inject(alias Page, Injectors...) () @property;

This function is useful if you need to support additional layers of functionality that should be available to your views, such as authentication. This function allows to define variables that should be usable from templates using so called "injectors". Each injector is a template function that can add its own parameters.

If you should need explicit access to one of the parameters of an upstream injector, you can use the InjectedParams!() template.


this function requires at least DMD 2.064, as it suffers from DMD BUG 2962/10086/10857.


The following example will render the template "home.dt" and make the variables 'userinfo', 'something_else' and 'message' available. Before the 'page' function is called, 'authInjector' and 'somethingInjector' can process the request and decide what to do.

void authInjector(alias Next, Aliases...)(HTTPServerRequest req, HTTPServerResponse res)
	string userinfo;
	// TODO: fill userinfo with content, throw an Unauthorized HTTP error etc.
	Next!(Aliases, userinfo)(req, res);

void somethingInjector(alias Next, Aliases...)(HTTPServerRequest req, HTTPServerResponse res)
	string something_else;
	Next!(Aliases, something_else)(req, res);

void page(Aliases...)(HTTPServerRequest req, HTTPServerResponse res)
	string message = "Welcome to the example page!"
	res.render!("home.dt", Aliases, message);

static this()
	auto router = new URLRouter;
	router.get("/", inject!(page, authInjector, somethingInjector));

Sönke Ludwig


© 2012 RejectedSoftware e.K.


Subject to the terms of the MIT license, as written in the included LICENSE.txt file.