I have some HTML code portions that repeat a lot through pages. I put this html code inside a function so that it is easy to maintain. It works perfectly. I, however feel this may not be very good practice.
function drawTable($item){
?>
HTML CODE HERE
<?php
}
I also run into the problem that when I want to return data using json the following won't work as it will be NULL:
$response['table'] = drawTable($item);
return json_encode($response);
What's the correct way to handle HTML code that repeats a lot??
Thanks
You may want to look into using templates instead of using ugly heredoc's or HTML-embedded-within-PHP-functions, which are just plain unmaintainable and are not IDE-friendly.
What is the best way to include a php file as a template?
If you have a repeating segment, simply load the template multiple times using a loop.
Although templates help with D.R.Y., the primary focus is to separate presentation from logic. Embedding HTML in PHP functions doesn't do that. Not to mention you don't have to escape any sort of quotes or break the indentation/formatting.
Example syntax when using templates:
$data = array('title' => 'My Page', 'text' => 'My Paragraph');
$Template = new Template();
$Template->render('/path/to/file.php', $data);
Your template page could be something like this:
<h1><?php echo $title; ?></h1>
<p><?php echo $text; ?></p>
function drawTable( $item ) { return '<p>something</p>'; }
function yourOtherFunction() {
$response['table'] = drawTable($item);
return json_encode($response);
}
Use this function definition
function drawTable($item){
return 'HTML CODE HERE';
}
Called with
print drawTable($item);
Which will also work for your json return value.
Related
This is my "code":
function whoop_function(){
return "whoop whoop!";
}
add_shortcode('whoop', 'whoop_function' );
Now when I want to use it in a post, all I get is:
[whoop]
As you can see I am very new and unused to it so maybe the answer is really simple, maybe I've just miss a thing in advance.
I both checked defining the function in functions.php and also in content.php
For shortcode function echo is required.
Please check with below code
function whoop_function(){
$responseData = "whoop whoop!";
echo $responseData;
return true;
}
add_shortcode('whoop', 'whoop_function' );
put your code in themes/function.php files and remove from content.php as function is duplicated so function already defined PHP error occurred.
function whoop_function(){
return "whoop whoop!";
}
add_shortcode('whoop', 'whoop_function' );
and add your shortcode [whoop] in any page content section.
if u use do_shortcode('[whoop]'); then echo it like below.
<?php echo do_shortcode('[whoop]'); ?>
Your approach is correct. I think you are using it in a template. Just need to use it as mentioned below :
In files:
<?php echo do_shortcode('[whoop]'); ?>
In admin pages or posts:
[whoop]
Fetch the content like this:
$post_content = get_post(get_id_by_slug('short')); // assuming that you have already defined get_id_by_slug function as you are using it in your code and "short" is a slug for post you are fetching content
$content = $post_content->post_content;
echo do_shortcode( $content );
You are fetching content without considering the short code. Update your code as above.
Hope it will work for you.
i would to know what is good practice for writing code to put all HTML code inside PHP function and in my front index.php file just call function to show code.
class.php:
public function test() {
$sql='select id,title from test ';
$nem=$this->db->prepare($sql);
$nem->execute();
$nem->bind_result($id,$title);
echo '<ul class="centreList">';
while($nem->fetch())
{
echo '<li>'.$id.'<a href="'.$title.'" >Download</a></li>';
}
echo '</ul>';
}
index.php:
<?php $connection->test(); ?>
This work fine, but I would like to know is this proper way or is not a good practice to use html code inside PHP functions?
It's ok to build HTML within PHP, but I would not echo to the screen directly from within the function. Instead, return the built HTML string.
$html = '<ul class="centreList">';
while($nem->fetch())
{
$html .= '<li>'.$id.'<a href="'.$title.'" >Download</a></li>';
}
$html .='</ul>';
return $html
The function should not be responsible for pushing content to the browser because it really limits what you can do with your code. What if you wanted to further process the HTML? What if you run into a condition later in the code and decided to abort? What if you wanted to set some response headers later? Some content would already be gone so none of these things would be possible without clever workarounds.
In general you want to separate your responsibilities: I would even break things down further:
one piece of code is in charge of retrieving info from the DB and returning
Another piece is in charge of building the HTML string
A third piece is in charge of displaying the HTML (probably your index.php)
New index.php
<?= $connection->test(); ?>
Do not use echo to print the html directly, wrap the html within while loop surrounded by php tags
public function test() {
$sql='select id,title from test ';
$nem=$this->db->prepare($sql);
$nem->execute();
$nem->bind_result($id,$title);
return $nem;
}
<ul class="centreList">
<?php $res = test()->fetch();
while( $res->fetch() ) { ?>
<li> <?php echo $id ?> Download </li>;
<?php } ?>
</ul>
I recently looked at my source code and it was a real mess.
my php source:
echo '<h1>Rar<h1>';
echo '<span>Rar</span>';
echo '<p>Rar</p>';
and when I view the browser source for the page rendered:
<h1>Rar</h1><span>Rar</span><p>Rar</p>
is there a way for me to override echo so that every output would end with a newline, something like
function echo($string)
{
echo $string . "\r\n";
}
echo is not a function, but a language statement. It cannot be redefined. If you are looking to prettify your output markup, have look at Tidy.
What you could do, is use your IDE's search/replace method and replace all echo statements with echo PHP_EOL,. This would append the OS specific newline char(s) before any output. Note the comma after PHP_EOL as it is important.
You can output several values with echo like this:
echo 'one', $foo, PHP_EOL,
'two', $bar, PHP_EOL;
so there is no need to write echo on each line.
However, I agree with anyone who suggested using a more dedicated approach to separate content and layout e.g. using template views or HereDoc.
In additon, there is very little gain in having pretty markup. If you are using tools like Firebug to inspect the HTML, you will have properly formatted markup regardless of the mess the markup really is. Moreover, on sites with a lot of visitors, you'll often find the markup minified, which is the opposite of what you are trying to do, simply because all these newlines and tabs add to the weight of the page, which leads to slower page loads and increased traffic cost.
You have various possibilities to output HTML.
You can use the heredoc syntax:
$html = <<<EOF
<h1>Rar<h1>
<span>Rar</span>
<p>Rar</p>
EOF
echo $hml;
Or (what is way better in my opinion), separate HTML from PHP. E.g. put all the PHP logic in the top of the file and the HTML after the PHP block:
<?php
// all your PHP goes here
$foo = 'bar'
?>
<!-- HTML comes here -->
<html>
<body>
<div>Hello <?php echo $foo; ?> </div>
</body>
</html>
Variables can be printed as shown above. But these variables don't contain HTML.
When you have to output HTML based on a condition, you can use the alternative syntax for control statements:
<?php if($some_condition): ?>
<h1>Rar<h1>
<span>Rar</span>
<p>Rar</p>
<?php endif ?>
This way it is also easier to debug your HTML as it is not only a PHP string.
You can set up and output buffer and then run the buffer through htmltidy. The tidy extension even has a specific function for the purpose. Just call this before you start outputting your html:
ob_start('ob_tidyhandler');
Although this solution does not override echo, you can get something close to echo with a newline. Add:
function e() {
return o::singleton();
}
class o {
private static $instance;
public static function singleton()
{
if (!isset(self::$instance)) {
$className = __CLASS__;
self::$instance = new $className;
}
return self::$instance;
}
public function __set($prop, $txt) {
echo $txt . PHP_EOL;
}
}
to your file, and then you can use:
e()->o = "Line which ends in newline";
instead of echo.
Another solution would be to separate your code from your layouts by using a proper templating engine.
You can indirectly overload echo() by using the __toString() magic method like so:
<?php
class CleanOutput
{
public $content;
public function __construct($c) {
$this->content= $c;
}
public function __toString() {
return $this->content . '\r\n';
}
}
$text= new CleanOutput('Hello world!');
echo $text;
?>
The above would output "Hello world!" with a newline and carriage return appended at the end. There's ways to further encapsulate this, but they are outside the scope of my answer.
Edit:
As was noted, the above solution is slow/clumsy. Here's a more elegant solution using output buffering:
<?
function clean_up($foo) {
return $foo . '\r\n';
}
ob_start('clean_up');
ob_implicit_flush(true);
echo "Hello world!";
?>
This is faster and cleaner (although it technically doesn't 'override' echo).
I haven't found anytihng in Google or the PHP manual, believe it or not. I would've thought there would be a string operation for something like this, maybe there is and I'm just uber blind today...
I have a php page, and when the button gets clicked, I would like to change a string of text on that page with something else.
So I was wondering if I could set the id="" attrib of the <p> to id="something" and then in my php code do something like this:
<?php
$something = "this will replace existing text in the something paragraph...";
?>
Can somebody please point me in the right direction? As the above did not work.
Thank you :)
UPDATE
I was able to get it working using the following sample:
Place this code above the <html> tag:
<?php
$existing = "default message here";
$something = "message displayed if form filled out.";
$ne = $_REQUEST["name"];
if ($ne == null) {
$output = $existing;
} else {
$output = $something;
}
?>
And place the following where ever your message is to be displayed:
<?php echo $output ?>
As far as I can get from your very fuzzy question, usually you don't need string manipulation if you have source data - you just substitute one data with another, this way:
<?php
$existing = "existing text";
$something = "this will replace existing text in the something paragraph...";
if (empty($_GET['button'])) {
$output = $existing;
} else {
$output = $something;
}
?>
<html>
<and stuff>
<p><?php echo $output ?></p>
</html>
but why not to ask a question bringing a real example of what you need? instead of foggy explanations in terms you aren't good with?
If you want to change the content of the paragraph without reloading the page you will need to use JavaScript. Give the paragraph an id.<p id='something'>Some text here</p> and then use innerHTML to replace it's contents. document.getElementById('something').innerHTML='Some new text'.
If you are reloading the page then you can use PHP. One way would be to put a marker in the HTML and then use str_replace() to insert the new text. eg <p><!-- marker --></p> in the HTML and $html_string = str_replace('<!-- marker -->', 'New Text', $html_string) assuming $html_string contains the HTML to output.
If you are looking for string manipulation and conversion you can simply use the str_replace function in php.
Please check this: str_replace()
If you're using a form (which I'm assuming you do) just check if the variable is set (check the $_POST array) and use a conditional statement. If the condition is false then display the default text, otherwise display something else.
I recently looked at my source code and it was a real mess.
my php source:
echo '<h1>Rar<h1>';
echo '<span>Rar</span>';
echo '<p>Rar</p>';
and when I view the browser source for the page rendered:
<h1>Rar</h1><span>Rar</span><p>Rar</p>
is there a way for me to override echo so that every output would end with a newline, something like
function echo($string)
{
echo $string . "\r\n";
}
echo is not a function, but a language statement. It cannot be redefined. If you are looking to prettify your output markup, have look at Tidy.
What you could do, is use your IDE's search/replace method and replace all echo statements with echo PHP_EOL,. This would append the OS specific newline char(s) before any output. Note the comma after PHP_EOL as it is important.
You can output several values with echo like this:
echo 'one', $foo, PHP_EOL,
'two', $bar, PHP_EOL;
so there is no need to write echo on each line.
However, I agree with anyone who suggested using a more dedicated approach to separate content and layout e.g. using template views or HereDoc.
In additon, there is very little gain in having pretty markup. If you are using tools like Firebug to inspect the HTML, you will have properly formatted markup regardless of the mess the markup really is. Moreover, on sites with a lot of visitors, you'll often find the markup minified, which is the opposite of what you are trying to do, simply because all these newlines and tabs add to the weight of the page, which leads to slower page loads and increased traffic cost.
You have various possibilities to output HTML.
You can use the heredoc syntax:
$html = <<<EOF
<h1>Rar<h1>
<span>Rar</span>
<p>Rar</p>
EOF
echo $hml;
Or (what is way better in my opinion), separate HTML from PHP. E.g. put all the PHP logic in the top of the file and the HTML after the PHP block:
<?php
// all your PHP goes here
$foo = 'bar'
?>
<!-- HTML comes here -->
<html>
<body>
<div>Hello <?php echo $foo; ?> </div>
</body>
</html>
Variables can be printed as shown above. But these variables don't contain HTML.
When you have to output HTML based on a condition, you can use the alternative syntax for control statements:
<?php if($some_condition): ?>
<h1>Rar<h1>
<span>Rar</span>
<p>Rar</p>
<?php endif ?>
This way it is also easier to debug your HTML as it is not only a PHP string.
You can set up and output buffer and then run the buffer through htmltidy. The tidy extension even has a specific function for the purpose. Just call this before you start outputting your html:
ob_start('ob_tidyhandler');
Although this solution does not override echo, you can get something close to echo with a newline. Add:
function e() {
return o::singleton();
}
class o {
private static $instance;
public static function singleton()
{
if (!isset(self::$instance)) {
$className = __CLASS__;
self::$instance = new $className;
}
return self::$instance;
}
public function __set($prop, $txt) {
echo $txt . PHP_EOL;
}
}
to your file, and then you can use:
e()->o = "Line which ends in newline";
instead of echo.
Another solution would be to separate your code from your layouts by using a proper templating engine.
You can indirectly overload echo() by using the __toString() magic method like so:
<?php
class CleanOutput
{
public $content;
public function __construct($c) {
$this->content= $c;
}
public function __toString() {
return $this->content . '\r\n';
}
}
$text= new CleanOutput('Hello world!');
echo $text;
?>
The above would output "Hello world!" with a newline and carriage return appended at the end. There's ways to further encapsulate this, but they are outside the scope of my answer.
Edit:
As was noted, the above solution is slow/clumsy. Here's a more elegant solution using output buffering:
<?
function clean_up($foo) {
return $foo . '\r\n';
}
ob_start('clean_up');
ob_implicit_flush(true);
echo "Hello world!";
?>
This is faster and cleaner (although it technically doesn't 'override' echo).