How to assign variables in twig? - php

Im migrating my code from smarty to twig
but I dont seem to find how to do this in twig
smarty:
$smarty->assign('Config',$Core->settings);
how can I do this in Twig ?

You would use 'set'. http://twig.sensiolabs.org/doc/tags/set.html
Then you would have to pass in $Core->settings as a variable from your controller like so:
return $this->render('my_template.html.twig', array(
'core_settings' => $Core->settings,
));
Then in my_template.html.twig you would use set like this:
{% set 'Config' = core_settings %}
I'm not sure if that works for you, Twig is different than smarty (I'm not very familar with smarty) but Twig is powerful.

Related

Pass two parameters as one to TWIG url

I'm using a framework (specifically EC-Cube3, if interested) that uses a Silex application with TWIG templates.
It has a navigation sidebar that is configured with PHP object arrays. I can inject an item array that looks something like this:
$item = array(
"id" => "item_id"
"url" => "named_url"
);
The url is created in typical Silex fashion:
$app->match('/item', 'Controller::method')->bind('named_url');
The framework eventually uses the url field and evaluates it in TWIG like so:
{{ url(item.url) }}
And this is usually fine! But the problem comes when I have a URL that includes a parameter, like this:
$app->match('/item/{id}', 'Controller::method')->bind('named_url'); // Needs 'id' to be evaluated.
In this scenario, setting the URL by the same array won't work because TWIG's url function needs the id for the second argument.
Since I can't change the application's TWIG files (because then I can't safely update the application), I need to be able to set the item's url to include the id as well.
After investigating, I don't think this is possible. Is it true that this is impossible? Or is there some method that I'm unaware of?
You can use mutiple vars like this
{{ path('path_in_route', {'id': article.id,'slug': article.slug}) }}
And
path_in_route
must be in your router file.
Hope that helps you.
Can you try the following in your Twig file:
{{ url(item.url,{'id': id}) }}
I believe that should work, but not certain.
EDIT #2
What if you use something like this:
$app->match('/item', 'Controller::method($id)')->bind('named_url');
Where $id is the id you need to pass in. I'm not really familiar with Silex, but maybe it's something like that?

Accessing other pages with Twig

I've started learning Twig today and wanted to know how I would redirect to another page in my template.
This is my index.php where I also load my homepage.
<?php
require '../vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('../recourses/views');
$twig = new Twig_Environment($loader);
echo $twig->render('pages/home.twig', array(
'project_title' => getProjectTitle()
));
Now my question is: How could I reach this page with an ?
I can't just use <a href ="pages/home.twig"> since it will show the code instead of the page itself.
I've tried searching but couldn't find my sollution.
Hope anyone can explain this to me.
If I unterstand, you are not using Symfony Standard Edition, but some Symfony components + Twig ?
In that case, Twig is only a a templating engine and Symfony functions are missing.
The path function (ShinDarth answer) is provided by a twig extension defined in the Symfony Standard Edition :
http://symfony.com/doc/current/reference/twig_reference.html#path
All the Symfony Standard Edition function are defined at the same page :
http://symfony.com/doc/current/reference/twig_reference.html
Using Twig like you do, you can only pass the path as variable and render it as {{ path_variable }}
Supposing that you have your route named my_route,
then via twig you simple do:
Link to my_route
Documentation: http://symfony.com/doc/current/book/templating.html#linking-to-pages

Laravel and Twig Bridge printing Auth object

I'm using Laravel basic authentication but I am really struggling to use the Auth object in the views.
There are good examples using Blade, but I am using Twig (twig bridge) and cannot solve this.
I can vardump(Auth::user()->name) in my controller in regular php but how do I get the same in the twig file (my view file)?
How do I do something like;
{% if auth.guest %}
Or;
{{ Auth.user().name }}
I've tried so many different ways but just get nothing.
This has to do with the way twig works, accessing static variables /classes or static methods on classes is impossible without adding a function to the Twig Environment.
You can register a function like so:
$twig = new Twig_Environment($loader);
$twig->addFunction('staticCall', new Twig_Function_Function('staticCall'));
function staticCall($class, $function, $args = array())
{
if (class_exists($class) && method_exists($class, $function))
return call_user_func_array(array($class, $function), $args);
return null;
}
Then i think you should be able to do:
{% if staticCall('Auth', 'guest') %}
Hi there stranger, why don't you login?
{% endif %}
I took the code from this answer: twig template engine, using a static function or variable

How use php "use" function in twig

In php I can use in my template:
use My\WebBundle\Classes\Util;
How can I put the same in Twig tempate?
Thanks.
You can't create objects in twig template, but you can pass them in twig template from controller:
public function postsAction() {
return $this->render('AcmeBlogBundle:User:posts.html.twig', array(
'util' => new My\WebBundle\Classes\Util(),
));
}
And in twig template can use it:
{{ util.anyProperty }}
You don't want PHP in your twig template. All you need to do is tell twig what variables you use. It's part of the MVC.
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

How to pass an array from Symfony 2 controller to a TWIG template ?

I can`t pass an array from a symfony 2 controller to a TWIG template. I use this code in the controller:
$searchTerms['color'] = "Red";
return $this->render('TestBundle::search.html.twig',
array(
"searchTerms" => $searchTerms));
In the twig template, I am trying to access the variable like this:
{{ searchTerms['color'] }}
{{ searchTerms.color }}
Both output nothing, empty string, so it seems like array comes to template but its elements are empty.
What`s wrong?
Yes, this code works. The first thing to check is that your twig code is in the correct page (TestBundle::search.html.twig). This might sound silly but that happens sometimes...
If this is all good, I suggest that you try to debug within your template. Debugging is the most important thing. You will always have this kind of problem while programming, especially when you try something new. The better you are at debugging your code, the better you are as a programmer because there is no way you can get everything right the first time.
So, how can you debug?
To debug within your twig template, you can use the debug extension of twig. To activate the debug option, you will have to do a quick change in your config file. You can also read this thread if your lost.
You can debug any variable within your template like this:
<pre>
{% debug searchTerms %}
</pre>
This way, you can easily debug your variable and test what your problem is:
{% debug searchTerms['color'] %}
If you want to debug things quickly, I highly recommend that you use the LadyBugBundle. It is an awesome tool that will allow you to do something like that:
In your controller:
ladybug_dump($searchTerms);
In your TWIG template:
{{ searchTerms|ladybug_dump }}
Not that different from a classic var_dump option, but if you have long arrays or objects, ladybug will impress you. More importantly, in a controller, you will often have the need to stop the code at a certain point to avoid the page to load after your debug statement, this is fairly easy with ladybug:
ladybug_dump_die($searchTerms);
You can even ask ladybug to load the "debugged" variable into Symfony profiler with this simple statement.
$this->get('ladybug')->log($searchTerms);
You have now direct access of the variable from a tab of the Symfony2 profiler.
Ladybug can do a lot more, but for this, the doc is really good.
I think you must change template like this:
{% for item in searchTerms %}
{{ item.color }}<br/>
{% endfor %}
See official documentation: Creating and using Templates->embedding-controllers

Categories