2

I'm currently finishing a client-website which has to be 100% valid HTML5. For one of the sections, I am using a matrix containing rich-text fields. This content is simply shown on the front page. The name of the client is "E&K".

Requirements:

  • The output contains HTML tags.
  • The output has to be 100% valid HTML.

Problem: The & character won't be escaped to & wherever it is outputted. This breaks the valid requirement. It seems the problem is the input, not the output. However the rich text editor keeps replacing manually placed & with &

How can I get this to work correctly?

1
  • If an answer provided the solution to your question it's good etiquette, and good manners, to mark it as the correct answer. Commented Jul 24, 2017 at 15:54

3 Answers 3

2

You could use Twig's replace filter on output:

{{ entry.richtext_field_handle|replace('&': '&') }}

At first glance I couldn't find a Redactor setting which would help you, but you might want to check yourself, or even write a Redactor plugin.

1

I finally found a way to do that using the "TwigPCRE" Craft plugin:

|preg_replace('/&(?!(?:[a-z]+|#x?\d+);)/', '&')|raw

This will replace all unescaped & characters which are not part of something else.

0

You don't have to escape the ampersand for it to be valid html5, and if it's appearing in content, not in a URL for example, then you really have nothing to worry about.

This validates:

<!doctype html>
<head>
  <title>E&K</title>
</head>
<body>
 <h1>E&K</h1>
</body>

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.