←back to thread

620 points tambourine_man | 4 comments | | HN request time: 0.586s | source
Show context
mounir9912 ◴[] No.43753471[source]
What I really don't get is how it's any different than applying whatever function you would apply to the template, on the f-string variables. So instead of:

   evil = "<script>alert('bad')</script>"
   template = t"{evil}"
   safe = html(template)
Why not just:

    evil = "<script>alert('bad')</script>"
    safe = f"{html(evil)}"
Or even before creating the f-string. Is it just about not forgetting the sanitization/string manipulation part and forcing you to go through that?
replies(2): >>43753514 #>>43757122 #
1. scott_w ◴[] No.43753514[source]
Pretty much, yeah. The article highlights that people were using f-strings directly, and they wanted to provide an alternative for lightweight template/interpolation.
replies(1): >>43753644 #
2. mounir9912 ◴[] No.43753644[source]
I feel like I'm still missing something when they're saying this about the example(s):

"Neither of these examples is possible with f-strings. By providing a mechanism to intercept and transform interpolated values, template strings enable a wide range of string processing use cases."

As far as I can see, anything you do with the template, you could do before building the f-string or inline as in my intial example.

replies(2): >>43753849 #>>43754429 #
3. scott_w ◴[] No.43753849[source]
You wouldn’t really do your example, though. If you’re using an f-string, you’d just directly interpolate, because it’s convenient. You wouldn’t use an extra library to properly make it safe, otherwise you’d just use a proper template library and language.

This gives you a convenient middle ground where you don’t need to learn a template library but still get safety. I can’t think of the code right now but I could see this being useful to pass in some dynamic HTML to, say, Django without having to remember to turn off escaping for that section. It can also be convenient for writing raw SQL without having to use prepared strings.

4. davepeck ◴[] No.43754429[source]
With f-strings, you cannot write code to determine which portions of the resulting `str` were static and which were dynamic; with t-strings, you can. *

(As to your initial example: it's worth considering what will happen as you compose multiple bits of HTML via nesting to generate a large final page. The developer experience may become... unideal.)

* (barring undesirable hacks with inspect, etc.)