I have this code in my Twig template:
{% for entity in entities %}
<ul>
<li>{{ entity.getName }} | Editar - Eliminar
{{ render(controller('ProductBundle:DetailGroup:index', { 'parent_id': entity.getId })) }}
</li>
</ul>
{% endfor %}
<dl class="sub-nav">
<dd>Add new</dd>
</dl>
<script>
$(function() {
$("#detail_group_create").click(function() {
loadCenterLayout(Routing.generate('detail_group_new'));
});
});
</script>
Because I'm calling this {{ render(controller('ProductBundle:DetailGroup:index', { 'parent_id': entity.getId })) }} I get the Add new link twice. I don't want to create a new function to handle the same, how did yours deal with this? Any tips or advice?
If I understood you correctly, you want to have index with dynamic center part of the layout. You either have to have:
separate controller functions or
single controller function but some GET/POST parameter and big IF/ELSE branching.
In second case you must not rely on #Template annotation (in case you use them) but rather on manually calling appropriate template render based on which branch you're in.
Did I get your issue right?
Related
I'm trying to show some object properties stored on the database. I've got the controller, the Entity, and the view. I'get no excepctions but I can't see the object properties.
Controller:
/**
* #Route ("/ov", name="ov")
*/
public function select(){
$a=$this->getDoctrine()->getRepository('AppBundle:PC')->find(2);
if(!$a){
throw $this->createNotFoundExcepction('No PC');
}
return $this->render('PcDetailed.html.twig', array('pcs' => $a));
}
View:
{% extends 'master.html.twig' %}
{% block divCentral %}
<div class="row">
<p>Nom del pc</p>
<div class="small-6 small-centered columns">
{% for pc in pcs %}
<p>{{ pc.nom }}</p>
{% endfor %}
</div>
</div>
{% endblock %}
Edit:
Finally, like Chris says, the problem is 'cause on the View I'm using I'm trying to iterate is an object, not an array. That's why doesn't work.
That's the way I must do it:
return $this->render('PcDetailed.html.twig', array('pcs' => array($a)));
In your controller you get the PC with id 2 and pass it to the view.
In the view you are now trying to iterate over this object. I have no idea what TWIG does when you try to iterate over something that is not an array or a collection but maybe it just fails silently.
To fix it, change your controller code to send an array to the view:
return $this->render('PcDetailed.html.twig', array('pcs' => array($a)));
Hie I am trying to get the synopsis and other items like author and published date printed. But I am Able to achieve this only with certain search terms, an error occurs with other words or terms
Key "description" for array with keys "title, subtitle, authors, publishedDate, industryIdentifiers, readingModes, pageCount, printType, categories, maturityRating, allowAnonLogging, contentVersion, imageLinks, language, previewLink, infoLink, canonicalVolumeLink" does not exist.
I am using symfony and twig. this is what the twig file looks like :
{% for item in items %}
<article>
<img src="{{ item.volumeInfo.imageLinks.thumbnail}}"/>
<h4>{{ item.volumeInfo.title}}</h4>
{{ item.volumeInfo.description }}
<strong> {{ item.volumeInfo.publishedDate }}</strong><br/>
<b>{{ item.volumeInfo.authors | join }}</b>
</article>
What am I doing wrong? why does this work only sometimes ? how can I make it work correctly all the time?
class GoogleBooksController extends Controller
{
public function getVolumeAction($title)
{
$client =new client();
$response = $client- >get("https://www.googleapis.com/books/v1/volumes?q=$title");
$data=$response->json();
$items=$data['items'];
return $this->render('BookReviewBundle:GoogleBooks:volume.html.twig', array('items'=>$items
// ...
)); }
Thanks
I belive the description field is not mandatory, so you can do follow
{% if item.volumeInfo.description is defined %}
{{ item.volumeInfo.description }}
{% endif %}
I define a template which built select dropdown inputs for my forms:
<p id="{{key | ucfirst}}">
<span>{{label}} : </span>
<select required disabled>
{% for d in data %}
<option value="{{attribute(d, optionValue)}}" {{(attribute(d, optionValue) == selectedValue)?'selected'}}>{{attribute(d, optionIntitule)}}</option>
{% endfor %}
</select>
<span><em>{{initialValue | default("")}}</em></span>
</p>
Then I just need to include it, and passing it some data:
{% include 'selectForm.twig' with {'label': 'Manager'
, 'key': context.manager.id
, 'initialValue': projet.manager.username
, 'data': users
, 'keyValue': 'id'
, 'keyIntitule': 'username'
, 'selectedValue': projet.manager.id) }
%}
It works fine, but I want to do more. For instance I would like to show a value more usefull for end user into option's label: <option>Username (email)</option> instead of <option>Username</option>
So I think I can't use anymore the attribute function.
I thought I could pass an expression to my template like following:
{% include 'selectForm.twig' with {..., 'keyIntitule': "#{d.username (d.email)}"} %}
But the expression is evaluated with immediate context, not template's one. So it doesn't work.
I also tried with template_from_string but I don't suceed in (I never used this function before...)
Is there a way to pass an expression to another template, and make it evaluate the expression with it's own context?
If you want to block the immediate context you can use include function instead of include tag. Then you can disable context this way (example taken from the documentation) :
{# only the foo variable will be accessible #}
{{ include('template.html', {foo: 'bar'}, with_context = false) }}
I found the solution with Twig's template_from_string function:
{% include 'selectForm.twig' with {..., 'keyIntitule': template_from_string("{{d.username}} ({{d.email}})")} %}
And then I use keyIntitule variable as a template:
<option value="{{attribute(d, optionValue)}}">{% include(keyIntitule) %}</option>
Works also with:
<option value="{{attribute(d, optionValue)}}">{{ include(keyIntitule) }}</option>
If you working with objects you could set keyIntitule to uniqueName and in the user entity define new method:
public function getUniqueName()
{
return sprintf('%s (%s)', $this->getUsername(), $this->getEmail());
}
Twig will call corresponding getter method. In this case uniqueName transforms to getUniqueName()
I have a twig template with the navbar and all other templates (the pages) include this template. I have a value in it which should be equal to all pages. How to set this value?
I tries something like this in a controller:
public function setNotificationsAction() {
$this->setNotifications();
return $this->render('AcmeMyBundle::navbar.html.twig', array(
'debts' => $this->notifications,
));
}
and then this in the template:
<span class="badge badge-important">
{% render(controller('AcmeMyBundle:DebtsLoansController:setNotifications')) %}
{{ debts }}
</span>
The result I want it like this:
<span class="badge badge-important">
3
</span>
but the number should be different and the controller should tell it.
I also tried to create a function which returns the value and to call it in the way like above.
I also tried this syntax
{{ render(controller('AcmeMyBundle:DebtsLoansController:setNotifications')) }}
but it isn't working, too.
I get the following mistake:
The function "controller" does not exist in AcmeMyBundle::navbar.html.twig at line 6
Do you have any idea how to achive this and not to have to edit each controller and each template :S Thanks very much in advance!
Well, I would suggest creating your own Twig extension. Something around the lines of:
<span class="badge">
{{ acme_notifications() }}
</span>
namespace Acme\DemoBundle\Twig\AcmeDemoExtension
class AcmeDemoExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
'acme_notifications' => new \Twig_Function_Method($this, 'getNotifications');
);
}
public function getNotifications()
{
$notifications = ...;
return $notifications;
}
}
Read more about creating your own Twig extension in the Symfony2 documentation.
You don't need the controller part :
{% render "AcmeBundle:MyController:MyAction" %}
Be aware however, that a render is a completely new request going through the whole Symfony lifecycle and thus can impact performance if you abuse it.
Edit : And as #Wouter J has pointed out : prior to Symfony 2.2 use above notation. After Symfony 2.2 the following has to be used :
{{ render(controller('AcmeArticleBundle:Article:recentArticles', { 'max': 3 })) }}
I'm wondering how to get the current page name, basically 'just' the last parameter in the route (i.e. /news or /about). I'm doing this because I want to be able to have the current page in the navigation highlighted.
Ideally, I'd like to store the current page name in a global variable so that in Twig I can just compare the current page name against the link and add a class accordingly.
I can't figure out how to add the current page name to a global variable though. I've tried using something like this:
$app['twig']->addGlobal('current_page_name', $app['request']->getRequestUri());
at the top of my app.php file, but an 'outside of request scope' error. But I wouldn't like to have to include this in every route.
What's the best way to do this?
If you put it into an app-level before middleware like this, that'll work:
$app->before(function (Request $request) use ($app) {
$app['twig']->addGlobal('current_page_name', $request->getRequestUri());
});
The "page name" part of your question is unclear, are you looking for the current route's name? You can access that via $request->get("_route") even in the before middleware, as it gets called when routing is already done.
You could also generate navigation list directly in stand alone nav twig template. And then import it in to the main template. Then you would only have to get silex to pass to the view the current page identifier. Simplest way... for example from Silex you would have to pass in the "path" variable to your view. Probably it would more convenient to to fetch nav_list from database and pass it in to twig template as global array variable instead. However this example is the simplest you could get to do what you intend.
nav.twig
{% set nav_list = [
["./", "home"],
["./contact", "contact"],
["./about", "about us"]
{# ... #}
] %}
{% set link_active = path|default("") %}
{% for link in nav_list %}
<li><a href="{{ link[0] }}" class="{% if link[0] == link_active %} activeClass {% endif %}" >{{ link[1] }}</a></li>
{% endfor %}
app.php
//...
$app->match('/about', function (Request $request) use ($app) {
return $app['twig']->render('about.twig', array(
'path' => './'.end(explode('/', $request->getRequestUri()))
));
});
//...