Escape functions in Blade templates?

Hi everyone,

With Sage 9 we now use blade’s {{ $variable }} to output any variable in templates.
So it means these variables are already escaped with htmlspecialchars().

But would you still run your variable through WordPress escaping functions like esc_html(), esc_attr(), esc_url(), etc?

Because the WP functions handle more specific cases (url, attribute,…) instead of a basic htmlspecialchars.

what would be the best practice here?

Thanks!

1 Like

You can use {!! esc_html($variable) !!}. See the Laravel Blade docs about this.

“Best practice” is probably up to whatever works best for you, but my preference is to do all necessary processing on my data before it reaches the blade. In other words, if I need esc_html(), I run that processing in my controller (or filter) and then pass the escaped data on to the blade. IMO blades should be use only to display data, not to modify it.

1 Like

Thanks Ben,

So on a general basis it still makes sense to use the esc_*() functions in combination with blade {{ }}, right?

Yeah, I’d say that’s probably a good idea.

If you wanted, you could also write a custom directive to use in place of {{$var}}, i.e. @escHtml($var).