leforestier / yattag

Python library to generate HTML or XML in a readable, concise and pythonic way.
328 stars 31 forks source link

Provide way to not escape attribute values #81

Closed abingham closed 1 month ago

abingham commented 1 month ago

I have a situation where I need to pass some structured data via an attribute. Here I'm specifying HTMX configuration through the content attribute:

doc.stag("meta", name="htmx-config", content='{"scrollBehavior":"auto"}')

Unfortunately, it seems that attribute contents get unilaterally escaped in simpledoc.attr_escape(), so that attribute value comes out mangled as <meta name="htmx-config" content="{&quot;scrollBehavior&quot;:&quot;auto&quot;}" />.

I don't see any mechanism to avoid this beyond, perhaps, using doc.asis(). Would you consider adding a means to avoid escaping attribute values? Perhaps something like this:

from yattag import AsIs
...
doc.stag("meta", name="htmx-config", content=AsIs('{"scrollBehavior":"auto"}'))

With this, attr_escape could look for instances of AsIs and not escape them. Perhaps there are other, better ways, but this is one option.

abingham commented 1 month ago

If it helps, I could probably put together a PR.

leforestier commented 1 month ago

What would you like the HTML output to be in that example?

abingham commented 1 month ago

Something like this: <meta name="htmx-config" content='{"scrollBehavior":"auto"}'/>. More generally, I think HTMX lets you do configuration by passing a JSON object as the value of content, so that needs to be preserved.

leforestier commented 1 month ago

Thanks, I understand the issue now. I like your idea of encapsulating these strings into AsIs objects to express the fact that they shouldn't be escaped. I would happily accept a PR.