Output string types from code in template languages not booleans etc

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the web-development category.

Last Updated: 2024-04-25

I had the following in a PHP blade file:

<? php

<input
  name="gender"
  type="checkbox"
  data-checked="{{ old('gender') == 'female' ? true : false }}"
/>

No matter what the contents of old('gender') was, I got no value for data-checked. This is because both true and false, the PHP booleans in the template here, may not evaluate to anything at all in the HTML.

The fix is to use strings explicitly in PHP when expected to produce strings to slot into the HTML frontend:

<? php
{{ old('gender') == 'female' ? "true" : "false" }}