I'm trying to figure out how to check for a single class on the body tag then include a file.
My header.php contains:
</head>
<?php $class = BODY_CLASS; ?>
<body class="<?php echo $class; ?>" id="top">
And in the body:
<?php if (isset($class) && $class == 'work') { ?>
<?php include( $_SERVER['DOCUMENT_ROOT'] . MODULES . "_social.php"); ?>
<?php }; ?>
This works fine so long as I only have a single class on the body tag, but what if I have multiple tags?
for instance my body tag outputs this:
<body id="top" class="work project1">
How can I check for the work even if other classes exist?
Just change your if statement a bit and explode() your $class, by a space to then search in the array for the value with in_array(), e.g.
if (in_array("work", explode(" ", $class))) {
You can use different approaches, for example, if you are sure that body class is always the first word, you can try this
$class=current(explode(" ",BODY_CLASS)); //class that you should check
if($class=='')
or
switch($class) { }
which splits the BODY_CLASS string and gets the first value.
Anyway, you can also try searching into an array, like this
if(in_array('classname',explode(" ",BODY_CLASS)))
You could use explode together with in_array:
if (isset($class) && in_array('work', explode(' ', $class))) { ...
References:
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.in-array.php
Related
I want to conditionally output HTML to generate a page, so what's the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?
echo '<html>', "\n"; // I'm sure there's a better way!
echo '<head>', "\n";
echo '</head>', "\n";
echo '<body>', "\n";
echo '</body>', "\n";
echo '</html>', "\n";
There are a few ways to echo HTML in PHP.
1. In between PHP tags
<?php if(condition){ ?>
<!-- HTML here -->
<?php } ?>
2. In an echo
if(condition){
echo "HTML here";
}
With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:
echo '<input type="text">';
Or you can escape them like so:
echo "<input type=\"text\">";
3. Heredocs
4. Nowdocs (as of PHP 5.3.0)
Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).
There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. {{someVariable}}).
The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run.
If you have any more questions feel free to leave a comment.
Further reading is available on these things in the PHP documentation.
NOTE: PHP short tags <? and ?> are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. They are available, regardless of settings from 5.4 onwards.
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
You could use the alternative syntax alternative syntax for control structures and break out of PHP:
<?php if ($something): ?>
<some /> <tags /> <etc />
<?=$shortButControversialWayOfPrintingAVariable ?>
<?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
<!-- else -->
<?php endif; ?>
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?> instead of <?=$var?> depending on your PHP setup.
I am partial to this style:
<html>
<head>
<% if (X)
{
%> <title>Definitely X</title>
<% }
else
{
%> <title>Totally not X</title>
<% }
%> </head>
</html>
I do use ASP-style tags, yes. The blending of PHP and HTML looks super-readable to my eyes. The trick is in getting the <% and %> markers just right.
Another approach is put the HTML in a separate file and mark the area to change with a placeholder [[content]] in this case. (You can also use sprintf instead of the str_replace.)
$page = 'Hello, World!';
$content = file_get_contents('html/welcome.html');
$pagecontent = str_replace('[[content]]', $content, $page);
echo($pagecontent);
Alternatively, you can just output all the PHP stuff to the screen captured in a buffer, write the HTML, and put the PHP output back into the page.
It might seem strange to write the PHP out, catch it, and then write it again, but it does mean that you can do all kinds of formatting stuff (heredoc, etc.), and test it outputs correctly without the hassle of the page template getting in the way. (The Joomla CMS does it this way, BTW.)
I.e.:
<?php
ob_start();
echo('Hello, World!');
$php_output = ob_get_contents();
ob_end_clean();
?>
<h1>My Template page says</h1>
<?php
echo($php_output);
?>
<hr>
Template footer
$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';
echo('Echo as HTML' . htmlspecialchars((string)$enter_string));
Simply use the print function to echo text in the PHP file as follows:
<?php
print('
<div class="wrap">
<span class="textClass">TESTING</span>
</div>
')
?>
In addition to Chris B's answer, if you need to use echo anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>'s, you can use the syntax below.
For example you want to display the images of a gallery:
foreach($images as $image)
{
echo
'<li>',
'<a href="', site_url(), 'images/', $image['name'], '">',
'<img ',
'class="image" ',
'title="', $image['title'], '" ',
'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
'alt="', $image['description'], '"',
'>',
'</a>',
'</li>';
}
Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo with parameters is more effective than concatenating.
echo '
<html>
<body>
</body>
</html>
';
or
echo "<html>\n<body>\n</body>\n</html>\n";
Try this:
<?php
echo <<<HTML
Your HTML tags here
HTML;
?>
This is how I do it:
<?php if($contition == true){ ?>
<input type="text" value="<?php echo $value_stored_in_php_variable; ?>" />
<?php }else{ ?>
<p>No input here </p>
<?php } ?>
Don't echo out HTML.
If you want to use
<?php echo "<h1> $title; </h1>"; ?>
you should be doing this:
<h1><?= $title;?></h1>
I'm using PHP as a template engine per this suggestion: https://stackoverflow.com/a/17870094/2081511
I have:
$title = 'My Title';
ob_start();
include('page/to/template.php');
$page = ob_get_clean();
And on page/to/template.php I have:
<?php
echo <<<EOF
<!doctype html>
<html>
<title>{$title}</title>
...
EOF;
?>
I'm trying to remove some of the required syntax from the template pages to make it easier for others to develop their own templates. What I would like to do is retain the variable naming convention of {$variable} but remove these lines from the template file:
<?php
echo <<<EOF
EOF;
?>
I was thinking about putting them on either side of the include statement, but then it would just show me that statement as text instead of including it.
Well, if you want a VERY simple templating solution, this might help
<?php
$title = 'My Title';
// Instead of including, we fetch the contents of the template file.
$contents = file_get_contents('template.php');
// Clone it, as we'll work on it.
$compiled = $contents;
// We want to pluck out all the variable names and discard the braces
preg_match_all('/{\$(\w+)}/', $contents, $matches);
// Loop through all the matches and see if there is a variable set with that name. If so, simply replace the match with the variable value.
foreach ($matches[0] as $index => $tag) {
if (isset(${$matches[1][$index]})) {
$compiled = str_replace($tag, ${$matches[1][$index]}, $compiled);
}
}
echo $compiled;
Template file would look like this
<html> <body> {$title} </body> </html>
I am trying to create a body class name based on a specific page in php. What I need to do is first define a variable and then check if the variable exists, and then if it exists display that one, otherwise if it is something else, then do something else, or if nothing then do not show any.
<body<?php if (defined('PAGE_KEY') && var == "homepage") echo " class=\"homepage\"";
elseif (defined('PAGE_KEY') && var == "page3") echo " class=\"page3\"";
elseif (defined('PAGE_KEY') && var == "page12") echo " class=\"page12\""; ?>>
This code will be located in my head.php.
My thought was to first check if variable was defined and if so then check what the variable was defined as and then based on that variable it will display a respective class.
The goal is for example on the page12 for the body tag to look like this:
<body class="page12">
But for example for the body tag on page55 (which I don't want to show a class for) to look like this:
<body>
In doing so I am able to now define css specifically for a page within the header where the body tag happens to be located.
Problem is first I don't know how to define the variable in the page, and second I don't know exactly how to write the php code above properly.
Attempt, for example on page12 I would have this code:
<?php PAGE_KEY = "page12" ?>
This code would be for example located in page12.php.
Also keep in mind, that the variable will come AFTER the body tag.
I also thought of trying to see what the page URL is but I think that's just making things too complicated.
Based on #Jordi's suggestion, how about this:
<body class="<?php echo PAGE_KEY ?>">
on head.php.
And then on page12.php, this:
<?php PAGE_KEY = "page12" ?>
and for example on page5.php this:
<?php PAGE_KEY = "page5" ?>
so that on those respective pages the body tag shows this:
on page5.php:
<body class="page5">
and on page12.php the body tag will show this:
<body class="page12">
Is this right?
#Jose made this suggestion, is this correct?
for example, on page12.php, to define the variable as 'page12', this:
<?php define("PAGE_KEY", "page12"); ?>
Is that what you were suggesting to do?
Ok! This problem is solved. I just needed to add in the code in the individual pages before the head.php include so I could define it. Thanks for your help! :)
You can use and define a constant like this :
<?php
define( "PAGE_KEY","homepage" );
?>
.
.
.
<body<?php echo " class=\"" . constant( "PAGE_KEY" ) . "\""; ?>>
For another page :
<?php
define( "PAGE_KEY","page5" );
?>
.
.
.
<body<?php echo " class=\"" . constant( "PAGE_KEY" ) . "\""; ?>>
You only change the constant, the rest is the same for every page.
Edit #1:
<body
<?php
define( "PAGE_KEY","homepage" );
echo " class=\"" . constant( "PAGE_KEY" ) . "\"";
?>
>
Edit #2:
<?php
define( "PAGE_KEY","homepage" );
?>
.
.
.
<?php
include( "head.php" >
?>
Now, head.php is something like this :
echo "<body class=\"" . constant( "PAGE_KEY" ) . "\">";
Start with something like this.
<?php
//each page and its class. Many pages can share the same class. If a page doesn't
//have a class, don't include it.
$classes = [
'homepage'=>'home_class',
'page1'=>'base_class',
'page2'=>'home_class',
'page3'=>'special_class'
];
//Adjust this from one page to the next
$this_page = 'homepage';
//get the class corresponding to current page, or '' if no class
$this_class = isset($classes[$this_page])? $classes[$this_page] : '';
?>
//insert the class for this page.
<body class="<?=$this_class ?>">
You can improve on it by moving the $classes array to another file (eg a config file) and including it in all your pages. This way you don't have to rewrite the array on every page (a bad idea because difficult to make a change, easy to make a mistake)
I'll just try to use explode function in tag system but its not work properly, first half is work but second half is not work, I'll explain my code and issue
Database structure : In a database structure create a one col for tag storage
Tag Col : first_tag,second_tag,tag,third_tag
Now My Code is:
<?php
if(!empty($data)) {
$str1=(explode(",",$data->tags));
$total=count($str1);}
if($data) {
for($i=0;$i<$total;$i++)
{ ?>
<?php echo explode('_',$str1[$i]);?>
<?php }} ?>
Result is : First Explode function is Work Properly
first_tag
second_tag
tag
third_tag
But Second Explode Function is not work : I need This Structure
first tag
second tag
tag
third tag
This Structure I need, please check my code
Maybe something such
if(!empty($data)) {
$str1=(explode(",",$s));
foreach($str1 as $str)
{ ?>
<?php echo str_replace('_', ' ', $str);?>
<?php }
} ?>
use preg_match instead like this
<?php
$data= "first_tag,second_tag,tag,third_tag";
if(!empty($data)) {
$str1=(explode(",",$data));
$total=count($str1);}
if($data) {
for($i=0;$i<$total;$i++)
{
preg_match( "/([a-z]+)_([a-z]+)|([a-z]+)/",$str1[$i],$matches);
?>
<?php echo $matches[1]." ".$matches[2]." ".$matches[3] ;?>
<?php }} ?>
this will produce
first tag
second tag
tag
third tag
I want to conditionally output HTML to generate a page, so what's the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?
echo '<html>', "\n"; // I'm sure there's a better way!
echo '<head>', "\n";
echo '</head>', "\n";
echo '<body>', "\n";
echo '</body>', "\n";
echo '</html>', "\n";
There are a few ways to echo HTML in PHP.
1. In between PHP tags
<?php if(condition){ ?>
<!-- HTML here -->
<?php } ?>
2. In an echo
if(condition){
echo "HTML here";
}
With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:
echo '<input type="text">';
Or you can escape them like so:
echo "<input type=\"text\">";
3. Heredocs
4. Nowdocs (as of PHP 5.3.0)
Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).
There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. {{someVariable}}).
The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run.
If you have any more questions feel free to leave a comment.
Further reading is available on these things in the PHP documentation.
NOTE: PHP short tags <? and ?> are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. They are available, regardless of settings from 5.4 onwards.
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
You could use the alternative syntax alternative syntax for control structures and break out of PHP:
<?php if ($something): ?>
<some /> <tags /> <etc />
<?=$shortButControversialWayOfPrintingAVariable ?>
<?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
<!-- else -->
<?php endif; ?>
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?> instead of <?=$var?> depending on your PHP setup.
I am partial to this style:
<html>
<head>
<% if (X)
{
%> <title>Definitely X</title>
<% }
else
{
%> <title>Totally not X</title>
<% }
%> </head>
</html>
I do use ASP-style tags, yes. The blending of PHP and HTML looks super-readable to my eyes. The trick is in getting the <% and %> markers just right.
Another approach is put the HTML in a separate file and mark the area to change with a placeholder [[content]] in this case. (You can also use sprintf instead of the str_replace.)
$page = 'Hello, World!';
$content = file_get_contents('html/welcome.html');
$pagecontent = str_replace('[[content]]', $content, $page);
echo($pagecontent);
Alternatively, you can just output all the PHP stuff to the screen captured in a buffer, write the HTML, and put the PHP output back into the page.
It might seem strange to write the PHP out, catch it, and then write it again, but it does mean that you can do all kinds of formatting stuff (heredoc, etc.), and test it outputs correctly without the hassle of the page template getting in the way. (The Joomla CMS does it this way, BTW.)
I.e.:
<?php
ob_start();
echo('Hello, World!');
$php_output = ob_get_contents();
ob_end_clean();
?>
<h1>My Template page says</h1>
<?php
echo($php_output);
?>
<hr>
Template footer
$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';
echo('Echo as HTML' . htmlspecialchars((string)$enter_string));
Simply use the print function to echo text in the PHP file as follows:
<?php
print('
<div class="wrap">
<span class="textClass">TESTING</span>
</div>
')
?>
In addition to Chris B's answer, if you need to use echo anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>'s, you can use the syntax below.
For example you want to display the images of a gallery:
foreach($images as $image)
{
echo
'<li>',
'<a href="', site_url(), 'images/', $image['name'], '">',
'<img ',
'class="image" ',
'title="', $image['title'], '" ',
'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
'alt="', $image['description'], '"',
'>',
'</a>',
'</li>';
}
Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo with parameters is more effective than concatenating.
echo '
<html>
<body>
</body>
</html>
';
or
echo "<html>\n<body>\n</body>\n</html>\n";
Try this:
<?php
echo <<<HTML
Your HTML tags here
HTML;
?>
This is how I do it:
<?php if($contition == true){ ?>
<input type="text" value="<?php echo $value_stored_in_php_variable; ?>" />
<?php }else{ ?>
<p>No input here </p>
<?php } ?>
Don't echo out HTML.
If you want to use
<?php echo "<h1> $title; </h1>"; ?>
you should be doing this:
<h1><?= $title;?></h1>