Am 31.01.2016 um 16:25 schrieb Martin Tschierschke:
In vibe.d's diet templates it is possible to use
"result: #{funktion_call(variable)} "
inside,
so that in the end"result: "~function_call(variable)!toString~" "
or something similar is evaluated.
How to use this in functionality in an other context?
Where in the vibe.d sources I can find this part of evaluation?Any hint for me?
Regards mt.
ps. First I thought it is an D feature...
It requires using a string mixin at the scope where the required
variables are accessible. A simple implementation:
import std.stdio;
import std.string;
// TODO: escape special characters properly with backslashes
string escape(string str) { return str; }
string writeInterpolated(string format)
{
string ret;
while (true) {
auto idx = format.indexOf('{');
if (idx < 0) {
ret ~= "write(\""~format.escape()~"\");\n";
break;
}
if (idx > 0) ret ~= "write(\""~format[0 .. idx].escape()~"\");\n";
format = format[idx+1 .. $];
auto eidx = format.indexOf('}');
assert(eidx >= 0, "Missing closing '}');
assert(eidx > 0, "Missing interpolation expression");
ret ~= "write("~format[0 .. eidx]~");\n";
format = format[eidx+1 .. $];
}
return ret ~ "writeln();";
}
void main()
{
string w = "world";
mixin(writeInterpolated("Hello, {w}!"));
}
Personally, I'm pretty happy with the printf
inspired syntax that is
supported by format
/writefln
/formattedWrite
. It also supports
positional arguments for things like i18n strings.