Say I have the following in my TPL file:
{$a}
and I want to apply certain PHP native functions (e.g. strip_tags) to that Smarty variable. Is this possible within the TPL? If so, how?
You can use any php function in a smarty template in the following way:
{$a|php_function_name}
or
{$a|php_function_name:param2:param3:...}
In the second example you can specify additional parameters for the php function (the first is always $a in our case).
for example:
{$a|substr:4:3} should result something like substr($_tpl_vars['a'],4,3); when smarty compiles it.
The best way is probably to create your own plugins and modifiers for Smarty. For your specific example, Smarty already has a strip_tags modifier. Use it like this:
{$a|strip_tags}
Very good question, it took me a while to completely figure this one out.
Call a function, passing a single parameter:
{"this is my string"|strtoupper}
// same as:
strtoupper("this is my string")
{$a:strtoupper}
// same as:
strtoupper($a)
Call a function, passing multiple parameters
{"/"|str_replace:"-":"this is my string"}
// same as:
str_replace("/", "-", "this is my string")
{"/"|str_replace:"-":$a}
// same as:
str_replace("/", "-", $a)
Or you can use this: (call function directly)
{rand()}
The whole point of templating systems is to abstract the creation of views from the underlying language. In other words, your variables should be prepared for displaying before they are passed to a templating engine, and you should not use any PHP functions in the template itself.
Smarty already has a Language Modifier built in for this.
{$a|strip_tags}
You don't need Native functions as there already integrated into the plugin system
http://www.smarty.net/docsv2/en/language.modifier.strip.tags.tpl
others here:
http://www.smarty.net/docsv2/en/language.modifiers.tpl
Related
Is there any project like PHP.js but in vice direction to provide PHP implementation of JS classes and functions? In particular Date, RegEx, String classes?
I found this class for String but I am looking for a more complete collection.
My consern is not about using or not using such thing, I just need such thing.
Today I found jsphp. It seems promising.
JavaScript for PHP (jsphp) is a pseudo-implementation of the ECMA 262
standard (JavaScript 8.5.1) for PHP 5.3+. It allows you to write code
in PHP as if it were JavaScript, using the standard API and the
dynamic attributes available in the language, such as prototype
inheritence and chaining, first-class functions, and other
object-orientated features. It includes JSBoolean, JSNumber, JSString,
JSObject, JSArray, JSFunction, JSRegExp, JSDate, JSError and JSMath,
as well as the global helper functions, such as parseInt or isNaN.
The syntax in jsphp is very similar to a native implementation, although adapted to the syntax of PHP. For example, the variables are
prepended by a "$", the Object access opertaor is "->", and Strings
are concatenated using a ".".
$myString = new JSString( 'Hello World' );
$myString = $myString->split( '' )->reverse()->join( '' );
print( 'Reversed: ' . $myString ); // dlroW olleH
There is not - and there can not be - somehting like you ask for.
Javascript has a special syntax for regular expressions, something PHP could not take.
Similar how "object" methods in javascript are invoked. And the scope of variables is different. So this would not work.
Instead use the PHP functions. If they are not complete or useable enough for you, wrap them into objects so you can create an interface you like. Or use one of the many libraries that are available.
How to assign a local template variable with a string concatenated just like below:
{$yes_src=const1.'yes'.const2}
to be used below in the code in the manner {$yes_src}.
By the way I am looking for a job as PHP developer :)
The way you are doing it is call the "short form" of assign, you just need to use the correct quoting mechanism:
{$yes_src="`$const1`yes`$const2`"}
Use assign:
{assign var="yes_src" val="`$const1`yes`$const2`"}
Use cat:
{$const1|cat:"yes"}{$const2}
You can also simply put the variables next to one another without assigning it to a variable:
{$const1}yes{$const2}
... no variable needed.
A note If you find yourself using assign more than rarely, you might have a misconception about the ideas of separating logic from presentation. Usually, concatenation and other variable work would be accomplished in PHP before the template is ever involved. The template's role is to just display the data, you should avoid creating or altering the data in the template.
Documentation
Smarty quotes - http://www.smarty.net/docs/en/language.syntax.quotes.tpl
Smarty assign - http://www.smarty.net/docs/en/language.function.assign.tpl
Smarty cat - http://www.smarty.net/docsv2/en/language.modifier.cat
{ $yes_src = $variable|cat:"some string"|cat:$variable }
Try this:
{capture assign=yes_src}{$const1}.'yes'.{$const2}{/capture}
And then use the new variable:
{$yes_src}
Just a simple question. I have a contact form stored in a function because it's just easier to call it on the pages I want it to have.
Now to extend usability, I want to search for {contactform} using str_replace.
Example:
function contactform(){
// bunch of inputs
}
$wysiwyg = str_replace('{contactform}', contactform(), $wysiwyg);
So basically, if {contactform} is found. Replace it with the output of contactform.
Now I know that I can run the function before the replace and store its output in a variable, and then replace it with that same variable. But I'm interested to know if there is a better method than the one I have in mind.
Thanks
To answer your question, you could use PCRE and preg_replace_callback and then either modify your contactform() function or create a wrapper that accepts the matches.
I think your idea of running the function once and storing it in a variable makes more sense though.
Your method is fine, I would set it as a $var if you are planning to use the contents of contactform() more than once.
It might pay to use http://php.net/strpos to check if {contact_form} exists before running the str_replace function.
You could try both ways, and if your server support it, benchmark:
<?php echo 'Memory Usage: '. (!function_exists('memory_get_usage') ? '0' : round(memory_get_usage()/1024/1024, 2)) .'MB'; ?>
you may want to have a look at php's call_user_func() more information here http://php.net/call_user_func
$wysiwyg = 'Some string and {contactform}';
$find = '{contactform}';
strpos($wysiwyg, $find) ? call_user_func($find) : '';
Yes, there is: Write one yourself. (Unless there already is one, which is always hard to be sure in PHP; see my next point.)
Ah, there it is: preg_replace_callback(). Of course, it's one of the three regex libraries and as such, does not do simple string manipulation.
Anyway, my point is: Do not follow PHP's [non-]design guidelines. Write your own multibyte-safe string substitution function with a callback, and do not use call_user_func().
I have this:
string {$one} = "$hello_"
string {$two} = "world"
How can I call the variable $hello_world from the above two string variables?
capture did not work for me.
Uses Smarty v2.5
{${$foo}{$bar}} will only work in Smarty3, though. In Smarty2 you'd have to write a plugin for that (or simply search the smarty forum, as there are plenty of solutions thereā¦)
From the documentation:
{$foo_{$x}} // will output the variable $foo_1 if $x has a value of 1.
So, you want:
{${$one}{$two}}
Since this functionality isn't allowed, I would recommend using a smarty plugin to mimic the behavior you want. Template plugins are just simple php functions, called via the $smarty->loadPlugin() method.
Smarty 2.x doesn't support variable variables.
Variables in smarty are actually stored inside the smarty object so you'd need explicit support in Smarty to use the convenient standard variable-variable syntax.
The following is the best I could come up with in Smarty 2.x. It uses a PHP block to store the value of the combined result for you.
{assign var="one" value="hello_"}
{assign var="two" value="world"}
{assign var="hello_world" value="HELLO!"}
{php}
$varname = $this->get_template_vars('one').$this->get_template_vars('two');
$this->assign('result', $this->get_template_vars($varname));
{/php}
{$result}
As mentioned, however, you have to get rid of the $ at the beginning of the value of $one. Otherwise you will need to modify it to the following line:
$varname = substr($this->get_template_vars('one'),1).$this->get_template_vars('two');
I and lately I'm seeing h() and e() functions in PHP. I have googled them, but they are so short that results don't give any idea of what they are. I got results like exponential or math related functions. For example:
<td><?php echo h($room['Room']['message']) ?></td>
Does anyone have an idea? or maybe they are not called functions? (I think I read about that very long ago, but I can remember its real name)
ADDED:
Thanks, for the replies. I am using CakePHP and also found an e() example:
<?php e($time->niceShort($question['Question'] ['created'])) ?>
If they were escaping somehow strings I think it would make sense, since I always see them right next the "echo"
I still don't know what they are ;(
As several readers have said, these are CakePHP-specific short-cuts. You can find them in the API docs at: here (for CakePHP 2.x)
I think I read that some of these are going to be removed in 1.3, personally I never used e() as typing echo really doesn't take that much longer :)
edit: e() is deprecated in 1.3 and no longer available in 2.0 see here
It looks like it might be CakePHP.
See e()
e (mixed $data)
Convenience wrapper for echo().
This has been Deprecated and will be removed in 2.0 version. Use
echo() instead.
See h()
h (string $text, string $charset = null)
Convenience wrapper for htmlspecialchars().
Most likely, they are dummy functions someone introduced for the sake of brevity. The h(), for example, looks like an alias for htmlspecialchars():
function h($s)
{
return htmlspecialchars($s);
}
So look for them in the include files. Espec. the ones with names likes "util.php" or "lib.php".
Likely the framework you're using is doing some escaping and has defined some short hands for htmlentities and htmlspecialchars or equivalents.
I'd do a search on whatever framework you're using for "function h("
They are probably functions defined and implemented by the group's code that you're looking at. I'm not aware of any e/h functions in the PHP language.
Nothing here:
http://us3.php.net/manual/en/function.h.php
http://us3.php.net/manual/en/function.e.php
There aren't any functions in PHP called h() and e(). They must be declared in the project you are working on. search for them and find out what they do.
In CakePHP h() is:
Convenience wrapper for htmlspecialchars()
For more information about Global constants and functions in CakePHP view this link
http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html
I'd guess that h() escapes user-submitted data for safe output, and e() escapes for database insertion. Whatever the functionality, these are not stock PHP functions.
It's CakePHP.
echo h('some stuff')
Is just htmlspecialchar()ing the stuff.
If you are using a decent editor press ctrl and click on the function. It should take you to the function's declaration.
http://book.cakephp.org/view/121/Global-Functions these are shortcut functions in cakePHP
Many of them are deprecated in 1.3 so beware of using them yourself
h() is global function in CakePHP. Documents about h() for CakePHP version 2.5.7 : http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#global-functions
Laravel also use e() helper function to runs htmlentities over the given string.
echo e('<html>foo</html>');
// <html>foo</html>
documentation : https://laravel.com/docs/5.8/helpers#method-e