Twig extend template on condition - php

I use Symfony 2 with Twig and my question is pretty straightforward:
In a view I want to extend one of the layouts based on a variable. If the variable is false I want to extend UdoWebsiteBundle::layout.html.twig and if it's true I want to extend UdoWebsiteBundle::layout_true.html.twig.
Here is the code I tried:
{% block layout_extender %}
{% if intro == 'false' %}
{% extends 'UdoWebsiteBundle::layout.html.twig' %}
{% else %}
{% extends 'UdoWebsiteBundle::layout_true.html.twig' %}
{% endif %}
{% endblock %}
I get this error:
Multiple extends tags are forbidden in "UdoWebsiteBundle:home:home.html.twig" at line 7
Is there any other way to achieve this?

Try this one:
{% extends intro == 'false'
? 'UdoWebsiteBundle::layout.html.twig'
: 'UdoWebsiteBundle::layout_true.html.twig' %}
Idea taken from here: http://jorisdewit.ca/2011/08/27/extending-different-layouts-for-ajax-requests-in-twig-symfony2/

To keep it neat you should use Twig dynamic inheritance support by using a variable, defined in your controller, as the base template:
{% extends parent_template_var %}
If the variable evaluates to a Twig_Template object, Twig will use it as the parent template.
Define parent_template_var in your controller:
if($intro == 'false')
$parent_template_var = 'UdoWebsiteBundle::layout.html.twig';
}else{
$parent_template_var = 'UdoWebsiteBundle::layout_true.html.twig';
}
return $this->render('::/action.html.twig', array('parent_template_var' => $parent_template_var ));
http://twig.sensiolabs.org/doc/tags/extends.html

Answer from the official documentation:
Conditional Inheritance
As the template name for the parent can be any valid Twig expression, it's possible to make the inheritance mechanism conditional:
{% extends standalone ? "minimum.html" : "base.html" %}
In this example, the template will extend the "minimum.html" layout template if the standalone variable evaluates to true, and "base.html" otherwise.

You cannot extends multiple template, that's why you've got the error, if you want to so, you need to push them in an array like below.
{% extends ['MyAppCustomBundle::Layout/layout.html.twig', 'FOSUserBundle::layout.html.twig'] %}
But you will need to use Twig version 1.2 to do it.
twig documentation

This all makes sense to do either this template or that template.
But let me describe another situation. You have a profile form and a form where users can upload personal profile related documents. Since the profile form is already very long the documents moved to a new form.
Everything works great. Now we want to use the bootstrap tabs to do Profile | Documents for user friendliness.
Now I know because we are using two seperate forms if you submit the documents the changes on the profile won't save and vice versa.
I have added the document form in the tab using
<div role="tabpanel" class="tab-pane" id="documents">
{{ render(controller('ManyAppBundle:Document:createDocument', {'viewOnly': true})) }}
</div>
The 'viewOnly': true is a query parameter and is not required by the action.
My question now becomes if the profile tab renders the document template it must only show the upload widget and the submit where as when you go directly to the document page it must show the title and side bar and everything. So I did try
{% if not viewOnly %}
{% extends ... %}
{% endif %}
That gave problems because you can't use extends within a if. Like you suggested in other answers try using
{% extends viewOnly == true ? ... %}
This reolved the Twig issue up to the execution of the code when viewOnly is false.
When viewOnly is false it must extend the base template used by all other templates but if it is true I only want to show this:
{{ form_start(form, { 'style': 'horizontal', 'col_size': 'sm' }) }}
{% if form.documents is defined %}
{{ form_row(form.documents) }}
{% endif %}
{{ form_row(form.submit, { 'attr': { 'class': 'btn btn-success' } }) }}
{{ form_end(form) }}
But now with the top
{% extends viewOnly == true ? ... %}
if viewOnly becomes false it fails with Template "" can't be find.
Is there a way to say extends this specific template that will be the same result of not extending any template?
Or alternatively is there a way of saying extend this when viewOnly true but nothing happens on the fail?

Related

Symfony how to include controller on base.html.twig

I have a small question, I'm new to symfony, I created a controller and a menu template that I want to integrate into my base.html.twig.
I absolutely need the controller to be called because I am testing to know if the session variable is empty or not.
{% block menu %}
{% include 'menu/index.html.twig' %}
{% endblock %}
<body>
{% block body %}{% endblock %}
</body>
So I tried this (it works perfectly BUT it didn't call my controller so when I do my test on session it won't work....)
I searched but I can't include the controller instead of the template...
thanks in advance
In Symfony, you cannot call a Controller from inside a twig, what you can do is store variables inside a Controller, and then call those variables from inside the twig.
For example, in your case, in the Controller you create your variable and save it in the session as follows:
//...
class BaseController extends AbstractController
{
//...
$session->set('var_i_need', 222);
return $this->render('menu/index.html.twig', [
'controller_name' => 'BaseController',
]);
}
Then inside the twig you get the variable:
{% set var_i_need = app.session.get('var_i_need') %}
And test if it is empty or not:
{% if var_i_need is not NULL %}
{% ... %}
{% endif %}
The controller shouldn't be called from a twig. EOT
You need to move your code from controller to service or helper.
Then you should run the service from controller.
Also, you need to create a new twig function and call service/helper code in this function.
This way the code form controller will be executed in twig - in the right way.

Symfony and Twig: conditions in templates

I have two bundles I created by my own: one to generate admin sections (AdminBundle), and another one to create bills (BillingBundle). BillingBundle has basically 2 entities: Client and Bill (1:m).
If I install both bundles to generate the new/edit forms and lists for Client and Bill at the admin, I include a part at config.yml like this:
my_admin_bundle:
entities:
project: #whatever entity. Project at AppBundle for example
new: true
list: true
client:
new: true
list: true
bill:
new: true
list: true
On the other hand, on AdminBundle I have a template called form.html.twig which renders the form to create new elements. Basically it is just like this:
{{ form(form) }}
The doubt: since the form to create new Bills need a .js file (accounting.js), how to include it only for new Bill form but not for new Client or Project forms ?
As you can imagine, now I have this in form.html.twig:
{{ form(form) }}
<script src="/bundles/ziiwebbilling/js/accounting.js" type="text/javascript"></script>
but I don't need accounting.js at form.html.twig for new Projects, or new Clients forms.
NOTE: sorry if I extend too much with my explanation, but I don't know how to explain it in another way. Even the title of the question is awful, please edit it if you find something better.
EDIT: as I've just wrote at the first comment for jkucharovic's answer, what I'm really looking for to solve my problem, is a non-intrusive way, that is: I wouldn't like to add the line about accounting.js inside an AdminBundle template. Or maybe am I looking for "too much"?
Use custom Twig extenstion with test function like this one:
public function getTests()
{
return [
new \Twig_SimpleTest('bill', function ($var) {
return $var instanceof Bill;
})
];
}
And then in template, you can simply test if form is for Bill entity:
{{ form(form) }}
{% if form.vars.value is bill %}
<script src="/bundles/ziiwebbilling/js/accounting.js"></script>
{% endif %}
Edit: If you don't want to modify template inside bundle for certain reason, you can make loading application-wide by defining own template and overriding default form block:
{%- block form -%}
{% if form.vars.value is bill %}
<script src="/bundles/ziiwebbilling/js/accounting.js"></script>
{% endif %}
{{ form_start(form) }}
{{- form_widget(form) -}}
{{ form_end(form) }}
{%- endblock form -%}

Difference between customizing form theme and referencing block in Symfony?

what is the difference between referencing a widget block and customizing it : the docs say :
So far, to override a particular form block, the best method is to
copy the default block from form_div_layout.html.twig, paste it into a
different template, and then customize it. In many cases, you can
avoid doing this by referencing the base block when customizing it
But to me it looks the same :
{# app/Resources/views/Form/fields.html.twig #}
{% extends 'form_div_layout.html.twig' %}
{% block integer_widget %}
<div class="integer_widget">
{{ parent() }}
</div>
{% endblock %}
{# app/Resources/views/form/fields.html.twig #}
{% block integer_widget %}
<div class="integer_widget">
{% set type = type|default('number') %}
{{ block('form_widget_simple') }}
</div>
{% endblock %}
What is the difference?
The first example in the documentation that you are referencing shows how to override the entire widget that displays your form element.
The second example in the documentation that you are referencing shows how you can employ code re-use so that you are not rewriting form templating sections that you are not modifying. So, instead of having to declare
{% set type = type|default('number') %}
{{ block('form_widget_simple') }}
all over again in your overriding widget, you can instead reference the base block that already has this. If you are referencing base blocks from an external template, you can call the parent block via {{ parent() }}, and if you are referencing blocks from inside the same template as the form, you can call the base block via {{ block('base_integer_widget') }}
If you look at it from a PHP/Symfony point of view with inheritance that can help explain it as well. Say you have one PHP class that extends another and you want to override a function named doSomething() - you might rewrite the entire function as you need it. But, say that doSomething() has a block of common code that you always want to run, then you might perform your actions and call parent::doSomething() at the end of it. Or, if you're accessing a different Symfony service you might call $this->get('some.service')->doSomething() instead.
That's the same concept here, you can either override the entire widget or you can override parts of it - perhaps putting a surrounding <div></div> but calling {{ parent() }} from within that since you're changing nothing else about the widget.
I do have one example where I overrode standard button behavior in Symfony and used both cases. I have a separate template file in `app/Resources/views/Form/navigationButton.html.twig' with the following code:
{% use 'form_div_layout.html.twig' %}
{% block button_widget -%}
{% set attr = attr|merge({class: (attr.class|default(''))|trim}) %}
{{- parent() -}}
{%- endblock %}
{% block button_row -%}
{{- form_widget(form) -}}
{%- endblock button_row %}
I am overriding the button widget by allowing additional classes to be passed as attributes and then calling the parent widget to produce it as normal. I then override the button row widget to not put surrounding <div></div> tags since I didn't want that in my template (see the originals here and here).
Then to use in one of my templates I simply do:
{% form_theme form ':Form:navigationButton.html.twig' %}

Inherit dynamic template in Phalcon Volt

I need to load a page, that will be "inserted" in a template - as I read it, Volt's Template Inheritance should do the trick and it does... kinda. Hardcoded values, as shown in the examples, work fine - the following example works:
<!-- Template -->
<div id="site_content">
{% block test %}
{% endblock %}
</div>
and the page, that inherits the template:
{% extends "../../templates/de/index.volt" %}
{% block test %}
{{ content() }} {# this is a registered volt function that outputs the generated content #}
{% endblock %}
However, the same page might need to inherit a different template and that must be decided on runtime, so the name of the template must be generated dynamically. Two options occurred to me:
Set the template name to a variable and use it when extending - the problem here is that I don't see a way to use it afterwards. That guy seems to have had the same problem, but there is neither an answer of how to do it, nor a confirmation that it isn't possible at all.
Register another function to generate the complete string (e.g. {% extends "../../templates/de/index.volt" %}) and then compile it, e.g.
$compiler->addFunction('get_template',
function ($resolvedArgs, $exprArgs) use ($volt) {
return $volt->getCompiler()
->compileString('{% extends "../../templates/de/index.volt" %}');
});
and then use that function in the page, e.g.
{{ get_template() }}
{% block test %}
{{ content() }}
{% endblock %}
However, using that approach does not parse the page content (e.g. the content returned by the registered content() function is not shown). I'm also open to other solutions (using Twig instead of Volt is only a last resort, for performance issues), advices of what I'm doing wrong or pointers of useful articles on the topic. Thanks in advance!
Try using partials as documented in the Phalcon doc: Using Partials

twig: pass variables from view to controller

Setup:
Twig 1.13.1
PHP 5.4.3
Problem:
I have 10,000 articles in my DB. I need a way to only allow X amount of stories to display on the page. I know I can limit the number in the controller before i call the template but that number will be different depending on the template that is used. I will have one controller to handles all the articles. I need a way to pass the number from the template to the controller to limit the array. I don't want to pull down all 10,000 articles then use twig "slice" filter/func.
I know in django you can use the below. That will only load the top 3 stories.
{% get_latest_stories 3 sports as story_list %}
{% for story in story_list %}
{{ story.title }}
{% endfor %}
Here is my current files.
Controller
<?php
$stories = news_stories::getStories("sports",5); //getStories(section,limit);
?>
<?=$twig->render("storyList.html", array('stories' => $stories))?>
View/Template
{% for story in story_list %}
{{ story.title }}
{% endfor %}
Summary
I would like a way to pass a number from the template to the controller so that i can limit the about of rows returned from the DB
Logically speaking, it would be impossible for the view to pass something to controller since the view is being processed at the end of the stack, after everything else.
You can however, pass a function into the view. You would want to create some sort of getViewStories function that you can access from your twig template. Since you have this already in your controller:
<?php
$stories = news_stories::getStories("sports",5); //getStories(section,limit);
?>
<?=$twig->render("storyList.html", array('stories' => $stories))?>
All you would need to do is change it around a bit, like this:
<?php
$function = new Twig_SimpleFunction('getViewStories', function (section, limit) {
return news_stories::getStories(section,limit);
});
$twig->addFunction($function);
?>
<?=$twig->render("storyList.html")?>
Now, from inside your template, you can call this function, like so:
{% set story_list = getViewStories('sports',5) %}
{% for story in story_list %}
{{ story.title }}
{% endfor %}
And change the getViewStories parameters around in each template.
And while you can use the slice filter, I would recommend against it in your case, as it makes for unnecessarily long database calls. This is the most optimized method (that I'm aware of).
You want to use the slice filter I think this should work for you
http://twig.sensiolabs.org/doc/filters/slice.html
{% for story in story_list|slice(1,5) %}
{{ story.title }}
{% endfor %}
should only return the elements 1 - > 5 of the loop then break loop. You can also do it like this
{% for story in story_list|[start:5] %}
{{ story.title }}
{% endfor %}
Disclaimer: I've never actually used twig though this was just a quick browse through its docs
You can embedded controllers ( or render other urls ) from inside a twig template. This means you could have a main layout template for your site, and keep your storyList.html template very plain - just to iterate over the stories and any markup they might need.
In your main layout you would render the action for the news stories:
<div id="stories">
{% render url('...') with { section: 'sports', limit: 5}, {'standalone': 'js'} %}
</div>
This way requires hindclude.js included on your page. Check these docs. If you are also using symfony ( you mention MVC but not the framework ) - even better. Scroll up a bit and look at Embedded controllers.
Otherwise, I believe this way essentially uses ajax.

Categories