Frank
Frank

Reputation: 36

How can I call a php variable inside html like smarty syntax?

I wants to know if someone have an idea of how can we call a variable inside html code like if we are using the smarty template.

<?php
$var = "sometext";
?>
<html>
<body>
<?php echo $var ?>
</body>
</html>

If we are using smarty template we can do like this:

<?php
$var = "sometext";
?>
<html>
<body>
{$var}
</body>
</html>

Is that possible without using smarty templates? Thank you for help!

Upvotes: 1

Views: 607

Answers (1)

Matt Prelude
Matt Prelude

Reputation: 912

You can't use Smarty syntax in 'naked' PHP... that's why it's Smarty syntax.

You have three options:

  1. Use PHP's builtin syntax, which is either <?php echo $var; ?> or <?= $var; ?> (there are good reasons not to use the second, mostly that it's difficult to comment out in PHP. You have to use HTML comments which leave remnants of PHP in your HTML source.)
  2. Write your own templating engine which parses your template files, you can use preg_match to search for a pattern like /\{(.*?)\}/ and replace them with the variables, but beware that code replacement causes complexities. If you want to go this route, look into output buffering and regex.
  3. Use Smarty or another templating engine you like. These libraries exist, so take advantage of them.

Note: in PHP 5.4 or newer, even if short tags are disabled, the short echo tag will work. Therefore, as long as you're not running unsupported old versions of PHP, you don't have to worry about access to it.

Upvotes: 2

Related Questions