class Test {
static function main() {
var s = "Hello ::recipient.name:: from company $$instance(::recipient.companies::,1,\"name\") ### ::foreach recipient.companies::::name::::end::";
var ctx : Dynamic = {
recipient: {
name : "Mrs. Annie Cordy",
companies : [ { name : "Company 1" }, { name : "Company 2" } ]
}
}
var tpl = new haxe.Template( s );
var out = tpl.execute( ctx, Test );
trace( out );
}
@:keep
static function instance( resolve:String->Dynamic, a : Array<Dynamic>, n : Int, field : String ){
return Reflect.field( a[ n ], field );
}
}
I succeed with that : Try Haxe ! , but if anyone has a better solution I take it
class Test {
static function main() {
var s = "Hello ::recipient.name:: from company $$instance(recipient.companies,1,name)";
var ctx = {
recipient: {
name: "Mrs. Annie Cordy",
companies: [{name: "Company 1"}, {name: "Company 2"}]
}
}
var tpl = new haxe.Template(s);
var out = tpl.execute(ctx, Test);
trace(out);
}
@:keep
static function instance(resolve:String->Dynamic, v:String, n:Int, field:String) {
var a = v.split( "." );
var o = resolve( a.shift() );
do {
o = Reflect.field( o, a.shift() );
}while( a.length > 0 );
var it : Array<Dynamic> = o;
return Reflect.field( it[ n ], field );
}
}
If your templates are available at compile time then tink_template is a good alternative to haxe.Template.
With it you should be able to do (: recipient.companies[1].name :), or could always call a function from the template anyway.
Thanks Valentin for your reply.
I yet use tink_template for my web templates that I found awesome. But here I need it on run-time. I found haxe.Template quite good but it misses some little things like that, that’s pitty.