how to put <b> tag in string in smarty template - smarty

I am using SMARTY and I need to put <b> tag in string in the following php code i can put tag in string
$search = 'this is my sample strangا';
$dbContent = 'this strang is for sample hello world';
$search = explode( ' ' , $search );
function wrapTag($inVal){
return '<b>'.$inVal.'</b>';
}
$replace = array_map( 'wrapTag' , $search );
$dbContent = str_replace( $search , $replace , $dbContent );
echo $dbContent;
how to use this code in smarty template or how to convert this code for smarty

In my opinion there's no need put such code into Smarty template, so the only thing you should do is
$smarty->assign('dbContent', $dbContent);
and in Smarty template file:
{$dbContent}
You should separate logic and display. In this case you shouldn't rather move this code to Smarty. If Your wrapTag function contained a lot of HTML you could do it this way ( I know global is not nice solution but probably it could be done also in the other way):
function wrapTag($inVal){
global $smarty;
$smarty->assign('inVal', $inVal);
return $smarty->fetch('bold_template.tpl');
}
and inside bold_template.tpl you could have:
<b>{$inVal}</b>
But if you only add <b> tags there's no point to put it in Smarty template

Related

Simple Dom Parser Returns Empty via Ajax

I'm using Simple HTML Dom Parser to correct some links in my output to good effect but have found some strange behaviour when calling content via Ajax. I'm using the parser on a WordPress site so feed the $content variable into the following function:
function add_trailing_slash( $content ) {
$content = str_get_html( $content );
if( $content ):
foreach( $content->find('a') as $a ):
if( isset( $a->href ) && '' !== $a->href && '#' !== $a->href ):
// replace http with https on all link hrefs
$a->href = str_replace('http:', 'https:', $a->href);
// checks if link lacks trailing slash and appends it if no extension (file)
$ext = pathinfo( $a->href, PATHINFO_EXTENSION );
if( '/' !== substr( $a->href, -1 ) && ! $ext ) $a->href = $a->href . '/';
endif;
endforeach;
endif;
return $content;
}
This is working great when added to the_content filter with add_filter( 'the_content', 'add_trailing_slash' ) and even when called directly like return add_trailing_slash( $output ) however, when I call the same function via Ajax I get a 'success' response but which is completely empty. Stranger still, I found that if I return the output via wpautop( $output ) it comes back just fine. wpautop (link) is essentially a bunch of preg_replace functions to replace double line breaks with <p> tags so I tested returning my output via return preg_replace('<blah>', '', $content) and it worked!
Oh, I also tested removing all my changes from the add_trailing_slash() function above and the same issue persisted so I guess that something to do with the way str_get_html( $content ) parses the input makes it not play well with the Ajax callback. But why does preg_replace make it returnable?
function add_trailing_slash( $content ) {
$content = str_get_html( $content );
return $content;
}
I'm wondering if anyone else has come across this issue, whether I'm missing something and this is expected or whether this is a bug? I could leave in my preg_replace which appears to 'fix' the issue but it feels like something of a hack.
The only thing that come to my mind is that when you do $content = str_get_html( $content ); you are getting an object as result. Maybe when it goes through wp functions it get interpreted like a string but when you are json_encoding it, something may go wrong and kill it. You can either try to force-cast it to string with
return (string) $content;
or try to use
// Dumps the internal DOM tree back into string
$str = $html->save();
as described in the docs

Getting 404 on images in public folder using a custom function in Laravel

I'm trying to use a simple function to auto-populate the images in a gallery page, but getting 404's on the images. Everything else is working as intended.
I'm using material css and all of that fluff is working correctly. I'm getting the correct number of image cards.
The path echoed out correctly, and within the function the name of the images is being generated with no issues. I'm using the {{asset}} function of Laravel and my images are in the public folder, so access shouldn't (?) be an issue.
public static function addImg($dirname){
$images = scandir($dirname);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
echo "<div class='col s12 m6 l4'>
<img src='{{asset({$dirname}{$curimg})}}' class='materialbox responsive-img card'>$curimg
</div>";
}
}
}
and the call is
{{$gallery::addImg('/css/img/')}}
Console shows "GET http://127.0.0.1:8000/%7B%7Basset(~snip for privacy~/public/css/img/hero%20(2).jpg)%7D%7D 404 (Not Found)"
You are using Blade syntax in a regular string. It isn't going to be parsed. You have to return the string how you actually need it to be.
Any interpolation you need has to be done while defining the string like any other regular string in PHP.
$location = asset($dirname . $curimage);
echo "<img src='{$location}' ...>{$curimage}";
Also you are calling {{ $gallery::addImg(...) }} which doesn't return anything that could be echoed by Blade. {{ }} is for echoing in Blade, it is not for just executing PHP statements.
This sounds like something you could make into a custom Blade directive though.
You can't use blade syntax inside a string because blade will parse only the .blade.php file.
But you can just use simple php concatenation:
public static function addImg($dirname){
$images = scandir($dirname);
$ignore = Array(".", "..");
foreach($images as $curimg){
if (!in_array($curimg, $ignore)) {
echo "<div class='col s12 m6 l4'>
<img src='" . asset($dirname . $curimg) . "' class='materialbox responsive-img card'>$curimg
</div>";
}
}
}

How to fill a rich text editor field for a Codeception Acceptance test

I'm trying to fill a rich text editor field (TinyMCE) within my acceptance test in Codeception.
Using the fillField() function doesn't work as this 'field' isn't really an input field. It's an iframe, styled to look like a fancy textarea.
How can I set some text into the body of the TinyMCE box? I think I'm looking for the addition of a $I->setContent(xpathOrCSS) function. Or does something else already exist to do this?
It is best to do this by adding re-usable actions to your Actor class (AcceptanceTester, by default). You can then use the actions in your tests to set the content of rich text editor fields without reducing the readability of your tests. More details on this are available in the Codeception documentation.
I have included solutions for TinyMCE and CKEditor below. The solution uses the executeInSelenium() call to give us access to Facebook's underlying WebDriver bindings. From there, we simply use the frame switching/Javascript injection technique described here to set the content of our target editor.
Note that the final call to $webDriver->switchTo()->defaultContent() is very important - this switches WebDriver's focus back from the RTE iframe to the page that contains it.
Actor functions:
<?php
class AcceptanceTester extends \Codeception\Actor {
use _generated\AcceptanceTesterActions;
public function fillCkEditorById($element_id, $content) {
$this->fillRteEditor(
\Facebook\WebDriver\WebDriverBy::cssSelector(
'#cke_' . $element_id . ' .cke_wysiwyg_frame'
),
$content
);
}
public function fillCkEditorByName($element_name, $content) {
$this->fillRteEditor(
\Facebook\WebDriver\WebDriverBy::cssSelector(
'textarea[name="' . $element_name . '"] + .cke .cke_wysiwyg_frame'
),
$content
);
}
public function fillTinyMceEditorById($id, $content) {
$this->fillTinyMceEditor('id', $id, $content);
}
public function fillTinyMceEditorByName($name, $content) {
$this->fillTinyMceEditor('name', $name, $content);
}
private function fillTinyMceEditor($attribute, $value, $content) {
$this->fillRteEditor(
\Facebook\WebDriver\WebDriverBy::xpath(
'//textarea[#' . $attribute . '=\'' . $value . '\']/../div[contains(#class, \'mce-tinymce\')]//iframe'
),
$content
);
}
private function fillRteEditor($selector, $content) {
$this->executeInSelenium(
function (\Facebook\WebDriver\Remote\RemoteWebDriver $webDriver)
use ($selector, $content) {
$webDriver->switchTo()->frame(
$webDriver->findElement($selector)
);
$webDriver->executeScript(
'arguments[0].innerHTML = "' . addslashes($content) . '"',
[$webDriver->findElement(\Facebook\WebDriver\WebDriverBy::tagName('body'))]
);
$webDriver->switchTo()->defaultContent();
});
}
}
Example Usage:
$content = '<h1>Hello, world!</h1>';
// CKEditor
$I->fillCkEditorByName('rich_content', $content);
$I->fillCkEditorById('my_ckeditor_textarea', $content);
// TinyMCE
$I->fillTinyMceEditorByName('rich_content', $content);
$I->fillTinyMceEditorById('my_tinymce_textarea', $content);
In all cases, the first parameter refers to the name/id attribute of the original textarea element, and the second parameter is the HTML content to fill it with.
Best way:
$I->executeJS('$("#selector").val("Value")');
If you have a simple setup and only need to test one instance in tinyMCE 4, this worked for me.
$I->executeJS('tinyMCE.activeEditor.setContent(" your content goes here ");');
IF you have and iframe like this:
<iframe id="myFrameID" allowtransparency="true"></iframe>
notice, that Codeception switches to the iframe using
$I->switchToIFrame("myFrameID");
Keep in mind, to omit the # in front of "myFrameID", as switch to iframe does not use a css selector but rather just the name of the iframe.
Then do
$I->executeJS('document.getElementById("tinymce").innerHTML = "<p>Some Text Here!</p>";');
and don't forget to switch back to previous window:
$I->switchToIFrame();
as stated in
https://codeception.com/docs/modules/WebDriver#switchToIFrame
Tried and following solution works:
$I->switchToIFrame('#frameName');
$I->executeJS('document.getElementById("tinymce").innerHTML = "<p>Test abc def</p>";');
try this
$x = $I->grabAttributeFrom('//iframe', 'id');
$I->switchToIframe($x);
$I->fillField('//*[#id="tinymce"]', '<p>Test abc</p>');

Codeigniter custom helper for bbcode, apply function on parameter

I made a custom bbcode parser function and added it on my helper
if ( !function_exists('bbcode_parser'))
{
function bbcode_parser($str)
{
$patterns = array(
'#\[b\](.*?)\[/b\]#is',
'#\[img\](.*?)\[/img\]#is',
'#\[url\](.*?)\[/url\]#is',
'#\[url=(.*?)\](.*?)\[/url\]#is'
);
$replacements = array(
'<strong>$1</strong>',
'<img src="$1" />',
'$1',
'$2',
);
$str = preg_replace($patterns, $replacements, $str);
return $str;
}
}
It's good and works like I want it to but my question is how to apply a function on each replacement value.
fe. for the url that doesn't have inner data, i want to replace with the website title of the url
or validate the url if it has http://
i would also like to check the size of the image, if it's too large, i want to resize it when printed by adding a "width" attribute and then just add an tag to the full size image.
is this possible? if so, how to do this?
You can implement this with preg_replace_callback()
http://www.php.net/manual/en/function.preg-replace-callback.php
Only the matched elements will be passed to the callback, so you would be able to create the callbacks you need or apply a standard replace for the normal regex patterns.

Incorrect characters in output

I'm trying to learn web scraping with Xpath. The code below works, however the output contains of incorrect characters and I can't manage to get this right.
Example:
Output: Emåmejeriet
How it should be: Emåmejeriet
PHP Code:
<?php
// Tried with these parameters but they doesn't make any difference
$html = new DOMDocument('1.0', 'UTF-8');
$html->loadHtmlFile('http://thesite.com/thedoc.html);
$xpath = new DOMXPath($html);
$nodelist = $xpath->query("//table");
foreach ($nodelist as $n) {
echo $n->nodeValue."\n";
}
?>
What can I do to fix this?
You should try encode() & decode() php functions if using ISO8859-15 or iconv() if not.
Example :
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
?>

Resources