The state of string interpolation...one year later

ag0aep6g anonymous at example.com
Sun Mar 17 14:01:36 UTC 2019


On 17.03.19 07:01, Jonathan Marler wrote:
> When I generate HTML documents in my cgi library, instead of:
> 
>      writeln(`<html><body>
>      <title>`, title, `</title>
>      <name>`, name, `</name><age>`, age, `</age>
>      <a href="`, link, `">`, linkName, `</a>
>      </body></html>
> `);
> 
> or even:
> 
>      writefln(`<html><body>
>      <title>%s</title>
>      <name>%s</name><age>%s</age>
>      <a href="%s">%s</a>
>      </body></html>
> `, title, name, age, link, linkName);
> 
> It will be:
> 
>      writeln(i`<html><body>
> 
>      <title>$title</title>
>      <name>$name</name><age>$age</age>
>      <a href="$link">$linkName</a>
>      </body></html>
> `);

Either way, you likely got yourself an HTML injection.

That might be the crux of string interpolation: It looks nice in simple 
examples, but is it still nice when you need to encode your variables 
for the output?

I think that should be a goal. We don't want to encourage writing bad 
code by making it more beautiful than correct code.

Unless I'm missing something (I've only skimmed your PRs), you don't 
have mechanisms to aid in this. So your example would look like this 
with encoding:

     writeln(i`<html><body>
         <title>$(title.toHTML)</title>
         <name>$(name.toHTML)</name><age>$(age.toHTML)</age>
         <a href="$(link.toHTML)">$(linkName.toHTML)</a>
         </body></html>
     `);

That might still be prettier than the alternative with a plain 
`writeln`, but the difference is less pronounced.

And with `writefln` we can do something like this:

     void writeflnToHTML(S ...)(string f, S stuff)
     {
         writefln(f, tupleMap!toHTML(stuff).expand);
     }
     writeflnToHTML(`<html><body>
         <title>%s</title>
         <name>%s</name><age>%s</age>
         <a href="%s">%s</a>
         </body></html>
     `, title, name, age, link, linkName);

That's still not pretty at all, but we can't forget a `.toHTML` this 
way. (Though `tupleMap` isn't in phobos and might be hard to get exactly 
right.)

Ideally, something like that would be possible with interpolated 
strings, too.


More information about the Digitalmars-d mailing list