Twig icon indicating copy to clipboard operation
Twig copied to clipboard

Mark safe object based on prop/method

Open I-Valchev opened this issue 4 years ago • 6 comments

Hi, I need to be able to mark an object as safe based on a prop value.

Following the docs, I can successfully add a safe class/interface. However, the use case is different. For example:

Field $a has safeHtml prop set to false -> not safe Field $b has safeHtml prop set to true -> should be safe (html rendered without using |raw in Twig itself).

I've looked at the code and PR that implements it, and tried the following:

  1. Custom escaper -> does not work, because by the time the escaper is called, the value is already cast to string, since the object implements __toString(). Hence, there's no longer access to safeHtml
  2. If the object does not implement __toString() then things like {{ a ~ ' something else' }} fail (a and b cannot be cast to string)
  3. Overriding html escaper -> does not work, since it's behaviour is hard-coded (see PR linked above)

Any guidelines to what can be done to support this? Thanks.

I-Valchev avatar Dec 15 '20 19:12 I-Valchev

Twig supports making some classes as safe regarding auto-escaping (Twig\Markup is always like that, but custom classes or interfaces can be registered too). But it does not have a way to make this safety conditional based on a property

stof avatar Dec 16 '20 11:12 stof

hi @stof, thanks for the info! Do you have any pointers of what needs to be done to get this to work? Either downstream in the app I'm working on, or as a PR in twig itself?

I-Valchev avatar Dec 16 '20 12:12 I-Valchev

Would it make sense to create a VO that encapsulates "safe" markup? So that if you pass in a value of this type, it won't be escaped?

apfelbox avatar Dec 17 '20 15:12 apfelbox

such VO already exist. What does not exist is the VO encapsulating "sometimes-safe" markup

stof avatar Dec 18 '20 12:12 stof

Sorry @stof and @apfelbox but... what is a VO? 🙈

I-Valchev avatar Dec 18 '20 14:12 I-Valchev

a value object

stof avatar Dec 18 '20 14:12 stof