Smarty - How to make functions? - php

I have tried making a function which I can run in the .tpl files.
I included a class Templates:
<?php
class Templates {
function getTemplate($template, $gameid) {
echo "test";
}
}
?>
Then I put this into the PHP page.
//Create a template object
$templates = new Templates();
$tpl->assign("template", $templates);
And then I try calling the function in the tpl file:
{$template->get('header',1)}
But I just get a blank page when I try this.
Any ideas how to actually do this?

You should probably look through the documentation on Smarty Plugins. These allow you to register your own functions which can be used just like the built-in tags and modifiers, or even custom sources of template data for use with the {include} function.
Your example is too stripped-down to guess what you actually want to achieve, so feel free to post a follow-up question if you can't see a way of achieving your specific goal.

Related

Latte - call function in TPL (ideally with parameter) instead of variable

I decided to rewrite an older website that I made years ago and use templating system. I decided to use Latte, as its generating PHP files, which makes it really fast compared to systems that parse tpl every time. But I was not able to figure out, how to call a function with latte and get its result.
I am used to our custom company TPL system which can call any function and even pass parameters to it just by calling {function_name.param} or use function constants with {function::param}.
Is something like this possible purely in Latte (I am not using Nette or any other framework)? I do not want to call every single function in PHP and add it to array of parameters that TPL has to its disposal. That just makes it slower (yep I know I could use ifs in there and then ifs in TPL, but that's also an useless code duplication).
I want it to be able to call a function within class that's rendering the TPL (or its parent classes OFC) and return its output when I need it (if I even do need it), so I can avoid unnecessary calls to functions when initializing parameters for TPL parsing.
I tried to google quite a lot, but I didn't find anything useful.
I should also mention, that I am not going to use any framework at all, except Latte with Tracy and Tester for automatic testing. I do not want to use Nette or Symfony 2 etc. as the site is not that big and using whole framework would just make it even more complicated than it needs to be.
Thanks.
.
Ps.: Could somebody create tag for Latte?
You can simply call any php function this way:
{? echo 'hello'}
or in newer versions of Latte:
{php echo 'hello'}
Also, you can pass instances of Nette\Utils\Html (small lib separated from framework, full of great tools even for small apps) which will be directly rendered.
Or if you want to use own class rendering output directly, simply implement __toString() function using IHtmlString interface:
class MyOwnClassRenderableByLatte implements \Latte\Runtime\IHtmlString
{
function __toString()
{
return 'Hi';
}
}
Template sample including your later questions:
{php
// You can instantiate needed classes in one synoptical block
// in the head of template file or reather instantiate them
// outside of template and pass them as template variables
$a = new ClassA();
$b = new ClassB();
}
<div>{$a->someFunction()}</div>
<div>
{* Or you can instantiate class inplace this way,
but I wouldn't recommend it. BTW: This is Latte comment.
*}
{php (new ClassC())->otherFunction()}
</div>
Try to use something like this, its same as with javascript
{some code} //is for latte expression
{ some other code} //with space after first bracket its no more latte expression
Not sure if your TPL will handle it, but you will see
If it will work, you can use more imagination and use something like
{
some fluffy code
}

Override a function in WordPress

Am having a plugin, In that I need to change some text it in, but this function doesn't have hook to use.
Usually the function will be override by using remove_action() or remove_filter(). For both the function we need filter name to override. But this plugin function doesn't add any filters.
Now I need to override this function.
For example
Plugin.php in plugin
function plugin(){
echo 'hello';
echo 'welcome you';
}
Function.php in theme
I want to the function plugin() in plugin.php to
function theme_plugin(){
echo 'hello';
echo 'You are welcome';
}
There is not add_action for plugin().
How to override the plugin() to theme_plugin()?
Look here Redefining PHP function?, you can't override php function or overload it. You have to find another way for solving your problem.
Regards,
If am right, you can us this link: http://sltaylor.co.uk/blog/customizing-new-user-email-pluggable-function/
**** Edit**
I have no much experience with wordpress. But here is someone asking for the same: Overriding a theme function from plugin in WordPress
And the marked answer is:
Unless the function is meant to be overridden, no. This is basic PHP. You can't redefine a function. If you try you will get a fatal error.
Parts of WordPress are written to be overwritten. Look at /wp-includes/pluggable.php. Every function in there is wrapped in a if( !function_exists(...) ) conditional. Unless your theme did the same, and some do for some functions, you can't overwrite.
Look around for filters that might help you instead.
Looking at your code, you should be able to unhook that. Just make sure to hook the unhook late enough. That is not a good solution, though since you are breaking theme functionality and also must know the know the names of all the hooked functions that themes are using.
Is there something in $fragments, or in $_POST or $_GET or anything else, that you can use to conditionally run your code, leaving the rest alone.
Anyway, Wordpress is opensource, so you can change the code by yourself? Why just change the plugin?

Whats the easiest way to use global variables in twig templates

I need to inject a HTML file from another website into my base.html.twig file.
One solution would be to use the php function 'file_get_contents' within my controller and make it available to the template like so:
$globalFooter = file_get_contents('http://mysite.co.uk/footer/footer.html.twig');
return $this->render('ImagineGdmBundle:Default:product.html.twig', array('globalFooter' => $globalFooter));
But that would mean having to implement the code above to every controller function that uses the footer. Is there a better way?
Im sure there must be a way to create a global variable and make them available to my base.html.twig template...but I am new to Symfony and am unsure how to do it. Any suggestions??
Question well explained in documentation about twig global variables. Your situation requires create twig extension. It would be a simlpe function that you can call anywhere in your templates.

Why do we need function_exists?

Why do we need to check function_exists for user defined functions? It looks ok for internal or core PHP functions but if user know and defined a function himself then why do need to check for its existance?
Below is custom user defined function
if( !function_exists( 'bia_register_menu' ) ) {
function bia_register_menu() {
register_nav_menu('primary-menu', __('Primary Menu'));
}
add_action('init', 'bia_register_menu');
}
Thanks
To make sure you don't register the same function twice, which will cause an error.
You also use if(function_exists('function_name')) when you are calling functions defined in plugins. In case you deactivated your plugin, your site will still be functional.
In dynamically loaded files using autoloaders, the file containing the function or class might not have loaded, so you need to check if it exists
This answer on the Wordpress StackExchange clarifies why you should sometimes use if function_exists around a function declaration in a theme:
The if function_exists approach allows for a child theme to override the function definition by simply defining the function themselves. Since child theme's functions.php files load first, then they will define the function first and the parent's definition will not get loaded.
I suppose it's analogous to the protected keyword in object oriented languages.
However I still wonder whether there would be any need for it around function declarations in plugins.
Imagine that you use you're URL to get the function name and call it.
Then we have the following info:
url: http://mysite.com/my/page/
When converting this url into a function name, you would do something like this:
implode('_', $myUrlPart); //my_page
The output would be "my_page" as string. But if you call this right away and the function does not exist, an error will be shown. This is where the function_exists comes in, take a look:
if (function_exists($function_name)) {
$function_name(); //the function is called
} else {
//call other function to show HTTP 404 page or something like that
}
Does this makes it a little clearer?
Because WordPress is designed so poorly it does not have any proper mechanism for autoloading modules like that, so you need to add safeguards.

Drupal Template Variables

Something that has been bothering me since I started using drupal is how exactly does the php engine know which $node/$classes/$attributes you are referring to in template files. these variables are never declared as globals, so how does the php engine figure out what "$node" you are referring to??
See http://drupal.org/node/223430 which states
The main role of the preprocessor is to set up variables to be placed
within the template (.tpl.php) files. From Drupal 7 they apply to
templates and functions, whereas in Drupal 6 preprocess functions only
apply to theming hooks implemented as templates. Plain theme functions
do not interact with preprocessors.
Look at the template_preprocess* and the template_process referred to in the API. These functions show you the code that set up the various variables that you can access in your node template.
In a similar manner, you can also add your own preprocess code in a theme function to add to the variables available in your tpl.php file like so:
/**
* Implements hook_preprocess_HOOK().
*/
function MY_MODULE_preprocess_node(&$variables) {
$variables['hello'] = 'Look at me now!';
}
After this, you can reference $hello in your node.tpl.php file.
These variables are set by Drupal's templating engine.

Categories