| |
| Posted by Walter Bright in reply to Adam D Ruppe | PermalinkReply |
|
Walter Bright
Posted in reply to Adam D Ruppe
| On 10/18/2023 7:47 PM, Adam D Ruppe wrote:
>> I'd like to see an example of code of how this customization might work, because I don't see it.
>
>
> Element makeHtmlFromTemplate(T...)(T t) if(T.length && is(T[0] == core.interpolation.InterpolationHeader!Parts, Parts...)) {
> string html;
> foreach(idx, str; Parts) {
> if(idx % 2 == 0)
> html ~= str; // i know this is html string literal thanks to noramlization
> else
> // note i also know what code this came from in case i need it for error messages, debug info, etc, it is in `str`
> html ~= htmlEntitiesEncode(to!string(t[idx / 2]));
> }
>
> return Element.make(Html(html));
> }
>
>
> auto element = makeHtmlFromTemplate(i`
> <html>
> <p class="foo" title="$(title)">
> $(content)
> </p>
> </html>
> `);
Thanks for the example. I thought I'd show the equivalent with DIP1027. It's a bit crude, and I didn't bother with the details of html generation, but this shows the method and can be compiled and run:
```
import std.conv;
string makeHtmlFromTemplate(Parts...)(const char[] fmt, Parts parts)
{
string html;
size_t i;
void advance()
{
while (i < fmt.length)
{
if (fmt[i] == '%' && i + 1 < fmt.length && fmt[i + 1] == 's')
{
i += 2;
return;
}
html ~= fmt[i];
++i;
}
}
advance();
foreach (part; parts)
{
html ~= to!string(part); // or htmlEntityEncode
advance();
}
return html;
}
void main()
{
import std.stdio;
string abc = "def";
string html = makeHtmlFromTemplate("format %s %s sss", abc, 73);
// tuple generated by DIP1027 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// from i"format $abc $(73) sss"
writeln(html);
}
```
which prints:
format def 73 sss
This code can be adapted to do whatever output schema one wants. Compare the tuple generated by DIP1027:
```
tuple("format %s %s sss", abc, 73)
```
and with YAIDIP:
```
tuple(.object.imported!"core.interpolation".InterpolationHeader!("", "format ", "", abc, "", 73, "", " sss", ""), "", "format ", "", abc, "", 73, "", " sss", "")
```
|