vibe.d beta banner
get vibe.d
0.7.30

Function inject

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

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.

Prototype

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

NOTE

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

Examples

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));
}
Authors

Sönke Ludwig

Copyright

© 2012 RejectedSoftware e.K.

License

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