How can I disable HTML validation for templates?

I’m trying to use PHP code within a template. For example, I have a _default/index.php template file containing something like this:

<p>Some text.</p>
<p>Some more text.</p>
echo "<div class='someclass'" . ($someObject->getSomeProperty() ? " style='color: red;'" : " style='color: blue;'") . ">Some other text.</div>";

This is a very simplified example, but hopefully you get the idea. When building the site, Hugo fails with the error:

"\"" in attribute name: "\" . ($someObject->getSomePropert"

I don’t know what to do to get this working. I’ve tried workarounds. I’ve tried moving the PHP code out into a partial template, and then using safeHTML:

{{ partial "test.php" . | safeHTML }}
{{ safeHTML (partial "test.php" .) }}

Yet it doesn’t make any difference. I just want it to not validate my HTML. Of course it’s not going to be valid HTML. It isn’t plain HTML. It’s HTML mixed in with PHP.

What can I do?

Never tried it myself but you should check out this piece about using php in hugo

To totally disable HTML validation/sanitation, you would have to look into output formats and the isPlainText setting. Setting that to true for an output format will then use Go’s text templates. This is why JSON templates behaves differently in Hugo.

Thanks a lot. Setting isPlainText = true worked. An alternative solution I found is to do something like this:

{{ readFile "themes/my-theme/layouts/partials/test-part.php" | safeHTML }}

Using readFile instead of partial bypasses the check entirely, I suppose. Between these two options I can make it work.

As for the “a dash of php” article - I actually read that already. Unfortunately it doesn’t apply to this situation. In that article, they discuss using shortcodes to add in PHP code to content files. In this case, I’m adding PHP to the templates themselves.

For some reason I always struggled understanding Ourput Formats’ IsPlainText parameter.

This thread helped.