Module template
String Templates.
In their simplest form they allow substitution of placeholders like
$(var)
with the value of var
determined by a lookup, which is
defined as a function plus an object.
StrTempl *st = str_templ_new("Hello $(P)$(name), how is $(home)?",NULL); // using an array of key/value pairs...(uses str_lookup) char *tbl1[] = {"name","Dolly","home","here","P","X",NULL}; char *S = str_templ_subst(st,tbl1); assert(str_eq(S,"Hello XDolly, how is here?")); // using a map - explicit lookup function and object Map *m = map_new_str_str(); map_put(m,"name","Monique"); map_put(m,"home","Paris"); map_put(m,"P","!"); S = str_templ_subst_using(st,(StrLookup)map_get,m); assert(str_eq(S,"Hello !Monique, how is Paris?"));
str_templ_subst_value
will use interface_get_lookup to see if the object
implements Accessor
, so the last could be simply written str_templ_subst_value(st)
since Map
defines that interface.
The placeholders can be changed if the default clashes with
the target language syntax, e.g. str_templ_new(str,"@<>")
. Then your template
will look like “this is @
Subtemplates can be defined; for instance this template generates an HTML list.
"<ul>$(for ls |<li>$(_)</li>|)</ul>"
There is an alternative syntax using a single colon instead of bracketting pipe characters.
"<ul>$(for ls: <li>$(_)</li>)</ul>"
The special for
form iterates over an Iterable
object like a List or an array.
The special variable \
refers to each value of the Iterable
; if we're iterating
over a map-like object, then it will be the key; use $([\
]) for the value.
See test-template.c
Functions
str_templ_new (templ, markers) | new template from string with variables to be expanded. |
str_templ_subst_using (stl, lookup, data) | substitute variables in template using a lookup function. |
str_templ_subst (stl, substs) | substitute the variables using an array of keys and pairs. |
str_templ_subst_values (st, v) | substitute using boxed values. |
Functions
- str_templ_new (templ, markers)
-
new template from string with variables to be expanded.
$(var)
is the default, ifmarkers
is NULL, but ifmarkers
was “@<>” then it would use ‘@’ as the escape and “<>” as the brackets.Parameters:
- templ const char *
- markers const char *
Returns:
-
StrTempl *
- str_templ_subst_using (stl, lookup, data)
-
substitute variables in template using a lookup function.
lookup
works withdata
, so that to use a Map you can pass map_get together with the map.Parameters:
- stl StrTempl *
- lookup StrLookup
- data void *
Returns:
-
char *
- str_templ_subst (stl, substs)
-
substitute the variables using an array of keys and pairs.
That is, a simple map.
Parameters:
- stl StrTempl *
- substs char * *
Returns:
-
char *
- str_templ_subst_values (st, v)
-
substitute using boxed values.
The value
v
can be any object supporting theAccessor
interface, or a simple map.Parameters:
- st StrTempl *
- v PValue
Returns:
-
char *