1

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!

4
  • 4
    Not without coding it, but you can use <?=$var?> Commented Sep 3, 2015 at 21:01
  • What's wrong with the first code block? Commented Sep 3, 2015 at 21:01
  • I know we can use <?=$var?>, but sometimes we have servers of that doesn't accept php short tag. That's why I'm trying to create something. But I believe there is no way if we not open the php tag first! Commented Sep 3, 2015 at 21:07
  • if you don't have short tags, then why not <?php echo? that's all <?= is, anyways Commented Sep 3, 2015 at 21:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.