Is there a concise way to include php variables in HTML? - php

All of the text on my page has to come from a translation file, so my markup is littered with stuff like <?php echo $translation; ?>.
For just one or two calls, it's fine, but when it's all over the page, it makes things awfully verbose. Is there a more concise way to include PHP variables in the markup? I can echo a heredoc, but then it removes all the IDE features for HTML editing like automatic indentation and highlighting.
Is there a way to just do something like {$translation} instead of <?php echo $translation ?>?

You can do
<?=$translation?>
If you have activated short_open_tag in your php.ini

You could use a template engine like smarty or twig. Smarty for example is supported in an IDE like netbeans.

Use a template language, like twig, it has builtin support for internatiolzation with a simple syntax.

If you want to keep "pure" PHP, you can use <?=$translation?>, or you can use a template engine, like Smarty. There are tons of those, just find one that suits you.

This should help you http://en.wikipedia.org/wiki/Template_engine_%28web%29

Related

What are some good tips for writing php files along side raw html?

I do not like spitting back html with php's echo, makes it hard to do and read nested elements. So I usually write conditions that write raw html and make it as readable as possbile when editing the file directly or viewing the output html through the browser. However, I cannot find a style that stays readable for long. Any suggestions?
<?
if($foo == $bar)
{
?>
<div>
<p>hello, world</p>
</div>
<?
}
?>
As you can see, it doesn't look too good. At least not to me, but it makes the browser output more readable so I can better check the it for any mistakes.
i dont want this:
<?
if($foo == $bar)
{
echo "<div>\n\t<p>hello, world</p>\n</div>\n";
}
?>
Is my approach incorrect to begin with? should I use php to output to a .html file? and just view from the browser for mistakes and do as much php as possible inside the php file?
Your right it's not nice, instead use proper alternative syntax, for content with a large amount of HTML:
<?php if($foo == $bar): ?>
<div>
<p>hello, world</p>
</div>
<?php endif ?>
I don't believe you need a seperate template language to write maintainable code, PHP is perfectly fine in outputting variables in HTML.
Really the problem is seperating your logic from your output which a template engine can't help with if your not structuring your code properly in the first place. For example stuffing it all in an index.php file or not using MVC whereas you don't put HTML with your logic.
If you have a large project or are overly concerned with separating your PHP from your views, or you want the features which come with a template engine like built in caching and slots etc, then use one. But maybe first look at learning a framework which will improve your overall codebase as most frameworks come with their own. Though essentially you can achieve the same thing including nesting partials and blocks/slots with a 20 line view class which uses ob_* functions, which doesn't require you to learn a new syntax.
Rant over.. :s
Use a templating system like Smarty so you can separate your logic from your display code.It also allows you to bring in a designer that can work with html and might not know php at all. Smarty templates read more like HTML than PHP and that can make a big difference when dealing with a designer.
Ansered by #boatcoder
You can learn here
Without the use of templating engine, your best bet is #Lawrence's answer or this littly modified syntax of your first exemple (trimminig space and php tag) :
<? if($foo == $bar) { ?>
<div>
<p>hello, world</p>
</div>
<? } ?>

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!
You can't use Smarty syntax in 'naked' PHP... that's why it's Smarty syntax.
You have three options:
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.)
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.
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.

How to use { in place of opening tags and } in place of closing tags?

I am an MVC addict.
I have some views in plain PHP (not using any Templating Engine (TE) such as Smarty for getting good performance), but without Smarty my views are looking ugly and hard to code.
I'm wondering how can I make them look good (ie., human readable) without using any TE? At least I want to replace those <?php and ?> for sure, or if you have any other better idea?
It's just a start of my web application so please guide me to any better alternative if you have any.
Thanks.
In templates I use the alternatives of PHP like:
<?php if (true): ?>
<?php endif ?>
<?php foreach ($x as $y): ?>
<?php endforeach ?>
etc.
http://php.net/manual/en/control-structures.alternative-syntax.php
There's no PHP variation or syntax that allows you to replace <?php and ?> with { and }. If you want that, you'll need to use or write a custom parser for it, which means you're looking at a templating engine. No templating engine, no custom syntax.

'echo' or drop out of 'programming' write HTML then start PHP code again

For the most part, when I want to display some HTML code to be actually rendered I would use a 'close PHP' tag, write the HTML, then open the PHP again. eg
<?php
// some php code
?>
<p>HTML that I want displayed</p>
<?php
// more php code
?>
But I have seen lots of people who would just use echo instead, so they would have done the above something like
<?php
// some php code
echo("<p>HTML that I want displayed</p>");
// more php code
?>
Is their any performance hit for dropping out and back in like that? I would assume not as the PHP engine would have to process the entire file either way.
What about when you use the echo function in the way that dose not look like a function, eg
echo "<p>HTML that I want displayed</p>"
I would hope that this is purely a matter of taste, but I would like to know if I was missing out on something. I personally find the first way preferable (dropping out of PHP then back in) as it helps draw a clear distinction between PHP and HTML and also lets you make use of code highlighting and hinting for your HTML, which is always handy.
The first type is preferable, exactly for the reasons you mentioned.
Actually, echoing out whole chunks of html is considered bad practice.
No, there's no performance increase that would be visible.
Sometimes its just simply easier to output content using echo (for example, when inside a while or for loop) than to close the php tag.
I think there's a preprocessor which converts the same form into the second. That's what happens in ASP.NET, anyway. And in both ASP.NET and classic ASP, loops can actually stretch across raw-HTML regions.
There's no performance difference at all.
Just the style that produces the most readable code. Depending on the actual situation that can be either of the two.
But mixing HTML and PHP should be avoided where possible anyway. THis can be accomplished by using a template system for your views.

Templates using php?

Whats the best way to create my own template engine using php, to transfer html templates into actual websites, and replacing the placeholders with the actual data... well, let me solve my own question...
class Template{
$private $output = '';
public function Load_Template($template){
ob_start();
include($template);
$this->output = ob_get_clean();
}
public function Replace($data){
$this->output = str_replace(array_keys($data), array_values($data), $this->output);
}
public function Display($add_footer = true){
echo $this->output;
}
}
This would work for a simple Template like...
<div>{username}</div>
But what would be the best way to do it with loops in my template.
Lets say something like
<ul>
<li>{username}</li>//Loop this line for each user
</ul>
Also, I dont want to use a third party engine like smarty, I would just like to know how to do it myself. Thank you
How about use php itself?
<div><?php echo $username ?></div>
<ul>
<?php foreach($users as $user): ?>
<li><?php echo $user->username ?></li>
<?php endforeach ?>
</ul>
*note: Funky endforeach syntax explained here.
Honestly, if I had to whip up my own template engine in PHP, I'd just use PHP. Just restrict yourself to only using variable interpolation and loops within the "templates".
Writing your own template engine is a tricky thing. You're inventing an entirely new language, after all, albeit a simple one. For it to be very powerful (i.e., beyond simple string replacement), you'd probably have to write an actual stack-based parser rather than rely on str_replace.
You could do this with regular expressions, much as you could parse HTML with regular expressions, but it won't be very reliable, easy to read, easy to debug, or easy to extend.
You mention that you don't want to use a third-party engine like Smarty, but you are basically setting out to do the exact same thing that Smarty is doing.
Something that people often overlook when talking about templating in PHP is that PHP is a templating language. There's no reason you can't just use regular old PHP inside your templates. In fact, that's what it was originally designed for.
If you really want to build your own templating engine, then you're going to have to sit down and design a syntax for looping and whatever other templating structures you'll want to use. Something like [do 5 times] { loop code }. Make up whatever you want. Then you'll have to parse it with PHP, and modify the template to replace it with the looped structure.
It's a big job... using normal PHP would be much easier.
Well, most of the answer to your question is preg_replace_callback().
I agree with everyone in this discussion - I have never understood the use of proprietary languages for templating in PHP - you know PHP so just use that.
If you are disciplined (e.g. follow MVC architectural pattern) in keeping a clear difference between PHP scripts that do things, and PHP that display things, there won't be any problems.
A couple of ways that can help are calling your PHP template files .phtml, and using alternative PHP syntax which is a little easier to maintain in templateswhich contain both HTML and PHP:
<?php if ( $a == $b ) : ?>
<strong>True</strong>
<?php else: ?>
<strong>False</strong>
<?php endif; ?>

Categories