cakephp element parameters with html - php

I want to render a cakephp element which contains static text. The element is supposed to contain help, text, images, ... etc. but it should show only the content relevant to the current page being rendered.
I thought of two ways, one of them is to simply pass html content as a parameter from the view as follows:
echo $this->element('help-bar-content', array(
'title' => 'Element title',
'help_text'=> '<div>
A lot of text and tags go here.
<br/>
<img class="img-class" src="/img/location"/>
</div>'
));
But it is ugly because it would mix html inside php which is inside html. The second way is to have a lot of elements each of them corresponding to a help_text parameter and use them as follows:
echo $this->element('help-bar-content', array(
'title' => 'Element title',
'help_text'=> element('help_element1')));
Which I think is better, But then I would have a LOT of non-reusable elements because I have a lot of views.
Is there a third (better) way to do this?

Put all the help texts in a switch statement or multiple ifs inside the element and give each one a string as identifier and pass that string to the element. Then display the text conditionally based on that string.
<?php if ($helpText === 'foo') : ?>
<p>foo</p>
<?php endif; ?>
Note $helpText follows the convention while $help_text doesnt.

Related

Treatment of PHP loops which are open and correct formatting

Very new to PHP and know a little HTML.
All these question spawned from the author's coding style. Which looks interesting, but then the way the code works doesn't seem to make sense.
I couldn't understand why the author is suggesting a separate <?php ?> tag for each line in html. Is this best style/coding practice?
Because of the author's style, I couldn't understand why the line <li><?php echo $product['name']; ?></li> is not put into a php tag of its own. For me "li" tag should sit inside the php tag, and then echoed out... but nope, what the author did works correctly to display the content.
Because of 2, I went to experiment with the code below. I've added in text where I think is just plain text where I expected to output once, and not go through a PHP loop. But nope... looping is happening even though the text is not in the PHP code itself.
Fully confused.
Any guidance is much appreciated.
<?php
$products = [
['name' => 'shiny star', 'price' => 20],
['name' => 'green shell', 'price' => 10],
['name' => 'red shell', 'price' => 15],
['name' => 'gold coin', 'price' => 5],
['name' => 'lightning bolt', 'price' => 40],
['name' => 'banana skin', 'price' => 2],
];
?>
<... snip to show only body..>
<body>
<div class="">
<ul>
Not php section
<?php foreach($products as $product) { ?>
Should be plain text with no repeat. Inside First. Outside second.
<?php if ($product['price'] > 15) { ?>
<li><?php echo $product['name']; ?></li>
Should be plain text. Inside second.
<?php } ?>
<?php } ?>
</ul>
</div>
</body>
Output:
Not php section Should be plain text with no repeat. Inside First. Outside second.
shiny star
Should be plain text. Inside second. Should be plain text with no repeat. Inside First. Outside second. Should be plain text with no repeat. Inside First. Outside second. Should be plain text with no repeat. Inside First. Outside second. Should be plain text with no repeat. Inside First. Outside second.
lightning bolt
Should be plain text. Inside second. Should be plain text with no repeat. Inside First. Outside second.
A general rule I go for is to only wrap PHP tags around the smallest thing possible.
So for the example, HTML tags don't NEED to be echoed, it's just the variables and loop that require it, so I would go for a similar style.
One way to think about it, is to think of text outside PHP tags like an implicit echo.
That might better explain why number 3 is tripping you up.
"Should be plain text with no repeat..." is between the opening and close braces of the foreach loop, so WILL be repeated.
So it's equivalent to something like this which would obviously repeat:
<?php
foreach($products as $product) {
echo "Should be plain text with no repeat. Inside First. Outside second.";
// ... the rest
}
?>
As #OsDev mentioned in the comments, when using PHP as a templating language in this way, it's also common to use the alternative syntax, which makes it easier to read without correct indentation. (if/while/for/foreach/switch all have alternative syntax versions)
I'd also recommend looking into templating languages such as Twig (Symfony framework) and Blade (Laravel framework), which are the more modern way of interspersing PHP and markup in modern PHP

Using HTML in Mandrill handlebar merge variables

If I have a handlebar merge variable like {{message}} in my template, how can I have it render HTML output if given the following in PHP:
array(
'name' => 'message',
'content' => '<p>First paragraph.</p><p>Second paragraph.</p>'
)
Right now it outputs the content without parsing the paragraph tags.
If you're using Handlebars I think the proper way to do it is with triple braces, e.g:
{{{html_content}}}
I'm not sure it is ok to mix mc:edit with Handlebars in Mandrill:
Combining Handlebars with either mc:edit regions or merge tags in a single message isn't supported. You should pick Handlebars or mc:edit regions plus merge tags.
https://mandrill.zendesk.com/hc/en-us/articles/205582537-Using-Handlebars-for-dynamic-content
Actually when sending using mandrill the message variable has a field merge_language and when you change to this
'merge_language' => 'handlebars'
It works. For your case i think the value is default 'mailchimp' hence the need to use mc:edit
To answer my own question, I just added mc:edit="message" to the div containing the message, like this:
<div mc:edit="message"></div>
I then added this to my structure:
$template_content = array(
array(
'name' => 'message',
'content' => '<p>First paragraph.</p><p>Second paragraph.</p>'
),
);

Print JSON preserving HTML tags

I want to write a simple WP plugin which will print some post data. Currently, I create an array, like this:
$arr = array(
'content' => get_the_content()
);
echo json_encode($arr);
Problem is - HTML in get_the_content is getting parsed. How can I prevent this?
Actually in this particular problem, since I need JSON, the simplest and the best way is to post header, like this:
header('Content-Type: application/json');
This will cause application to treat the file (either named aaa.json or index.php) as JSON.
htmlspecialchars() should solve your problem.
It will replace html-specific characters with their "entity codes". F.ex. < becomes <, etc.
And when printed to a page, these entities will be displayed as they were originally, except they won't be accepted as part of an html tag.

Simpe_html_dom: How to remove a 'div' tag with a particular 'class' attribute?

How can remove all the div tags with the class attribute equal to info in a PHP page, i.e. the <div class="info">...</div> tags need to be removed from an HTML string.
I have seen this question, but I want to remove elements with the class equal to info.
I will like to use Simple HTML DOM (compared to any other library) because I am already using it in the program.
There are multiple ways to select elements by class. Check out the manual.
$html->find('div[class=info]');
$html->find('div.info');
$html->find('.info'); // not just divs
Then using this answer, you can remove the elements by setting outertext to be blank. In a loop it might look like this:
foreach($html->find('div.info') as $node) {
$node->outertext = '';
}
Edit: this is a good article which seems to cover most aspects of manipulation and common pitfalls (including deleting data).

Add HTML form with dynamic attribute values

The page I'm currently working on has an "add another" option, which inserts a fieldset containing a title and a list of 3 input boxes. Each of these input boxes, for form submission sake, needs to be given a name with an incremented value. ("field1_1", "field1_2" etc)
I know that I could add the fields by dynamically creating elements with $('<input/>', {...}); but for more than a few elements this makes for code that's hard to read and difficult to maintain.
I'm currently using jQuery's .load() function to pull in the file but through searching I can't find a way to pass variables to the response, and therefore can only use preset name attribute values.
Is this possible, or is the method above the only way?
Put your template into a dummy script, with unknown type to avoid errors:
<script id="template1" type="text/template">
<h2>{title}</h2>
<input type="text" name="field{id}_1">
<input type="text" name="field{id}_2">
<input type="text" name="field{id}_3">
</script>
Then use replace (with "g" global option as replace usually replaces first only) to insert your values.
var template = $('#template1').html();
template = Template.replace(/\{title\}/g, mytitle);
template = Template.replace(/\{id\}/g, nextId);
$('#somewhere').append(template);
You can of course concatenate the replaces, but going for readable here.
This method allows complex HTML without messing up the code with loads of string manipulation. Your template looks like the final result so no mental translation required. Very low-maintenance technique.
The placeholders can just be simple names (without braces) to avoid regex delimiters, so long as the names will not match anything else in the template. I just use braces so the placeholders stand out in the template (again for maintenance purposes).

Categories