I work a lot in mixed HTML and PHP and most time I just want solid HTML with a few PHP variables in it so my code look like this:
<tr><td> <input type="hidden" name="type" value="<?php echo $var; ?>" ></td></tr>
Which is quite ugly. Isn't there something shorter, more like the following?
<tr><td> <input type="hidden" name="type" value="$$var" ></td></tr>
This is possible to but you get stuck with the ""
(you have to replace them all with ''
) and the layout is gone
echo "<tr><td> <input type="hidden" name="type" value="$var" ></td></tr>"
Is there anything better?
Use the HEREDOC syntax. You can mix single and double quotes, variables and even function calls with unaltered / unescaped html markup.
echo <<<MYTAG
<tr><td> <input type="hidden" name="type" value="$var1" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var2" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var3" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var4" ></td></tr>
MYTAG;
I'd advise against using shorttags, see Are PHP short tags acceptable to use? for more information on why.
Personally I don't mind mixing HTML and PHP like so
<a href="<?php echo $link;?>">link description</a>
As long as I have a code-editor with good syntax highlighting, I think this is pretty readable. If you start echoing HTML with PHP then you lose all the advantages of syntax highlighting your HTML. Another disadvantage of echoing HTML is the stuff with the quotes, the following is a lot less readable IMHO.
echo '<a href="'.$link.'">link description</a>';
The biggest advantage for me with simple echoing and simple looping in PHP and doing the rest in HTML is that indentation is consistent, which in the end improves readability/scannability.
There are plenty of templating systems that offer more compact syntax for your views. Smarty is venerable and popular. This article lists 10 others.
In a php section before the HTML section, use sprinf() to create a constant string from the variables:
$mystuff = sprinf("My name is %s and my mother's name is %s","Suzy","Caroline");
Then in the HTML section you can do whatever you like, such as:
<p>$mystuff</p>
I really think you should adopt Smarty template engine as a standard php lib for your projects.
Name: {$name|capitalize}<br>
Source: Stackoverflow.com