EzDevInfo.com

twig interview questions

Top twig frequently asked interview questions

How to get config parameters in Symfony2 Twig Templates

I have a Symfony2 Twig template. I want to output the value of a config parameter in this twig template (a version number). Therefore I defined the config parameter like this:

parameters:
    app.version: 0.1.0

I'm able to use this config parameter in Controllers but I have no clue how to get it in my Twig template.


Source: (StackOverflow)

How to check for null in Twig?

What construct should I use to check whether a value is NULL in a Twig template?


Source: (StackOverflow)

Advertisements

AngularJS-Twig conflict with double curly braces

As you know, both angular and twig has common control construction - double curly braces. How can I change default value of Angular?

I know that I can do it in Twig, but in some projects I can't, only JS.


Source: (StackOverflow)

How to access class constants in Twig?

I have a few class constants in my entity class, e.g.:

class Entity {
    const TYPE_PERSON = 0;
    const TYPE_COMPANY = 1;
}

In normal PHP I often do if($var == Entity::TYPE_PERSON) and I would like to do this kind of stuff in Twig. Is it possible?


Source: (StackOverflow)

How do you check if an object exists in the Twig templating engine in Symfony2?

I have a multidimensional array where some objects exist and others don't. I keep getting a

Method "code" for object "stdClass" does not exist in...?

The code I am using in my template is:

{% for item in items %}
    <p>{% if item.product.code %}{{ item.product.code }}{% endif %}</p>
{% endfor %}

Some products do not have this code and unfortunately this data structure is provided via a feed, so I cannot change it.

When I looked at the Twig documentation I interpreted that if an object or method was not there it would just return null?


Source: (StackOverflow)

How to render a DateTime object in a Twig template

One of my fields in one of my entities is a "datetime" variable.

How can I convert this field into a string to render in a browser?

Here is a code snippet:

{% for game in games %}
    ...
        <td> {{game.gameTeamIdOne.teamName}} </td>
        <td> {{game.gameTeamIdTwo.teamName}} </td>
        <td> {{game.gameDate}}</td>
    </tr>
{% endfor %}

Here is the variable in my entity class:

/**
 * @var date $gameDate
 *
 * @ORM\Column(name="GAME_DATE", type="datetime", nullable=true)
 */
private $gameDate;

And here is the error message I am getting:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class DateTime could not be converted to string in ...\app\cache\dev\twig\9b\ad\58fd3bb1517632badf1fdc7fa4a8.php line 33") in "BeerBundle:Games:gameTable.html.twig" at line 10.


Source: (StackOverflow)

How to var_dump variables in twig templates?

View layer pattern where you only present what you have been given is fine and all, but how do you know what is available? Is there a "list all defined variables" functionality in TWIG? Is there a way to dump a variable?

The solution I found by searching for it was to define a function where I can use my existing php debug tools by injecting a function, but all references I have found to that includes these nice two lines of code, but nowhere is it specified where to place them. Going by the fact that they need a $loader variable defined, I tried /app/config/autoload.php but the $loader there was the wrong kind. Where do I place the php code for adding a twig function?


Source: (StackOverflow)

Get the environment name in a Twig template with Symfony2

Is there a way to get the name of the current environment in a Twig template? I'd like to set some CSS style values depending on it.


Source: (StackOverflow)

Twig: in_array or similar possible within if statement?

I am using Twig as templating engine and I am really loving it. However, now I have run in a situation which definitely mustbe accomplishable in a simpler way than I have found.

What I have right now is this:

{% for myVar in someArray %}    
    {% set found = 0 %}
    {% for id, data in someOtherArray %}
        {% if id == myVar %}
            {{ myVar }} exists within someOtherArray.
            {% set found = 1 %} 
        {% endif %}
    {% endfor %}

    {% if found == 0 %}
        {{ myVar }} doesn't exist within someOtherArray.
    {% endif %}
{% endfor %}

What I am looking for is something more like this:

{% for myVar in someArray %}    
    {% if myVar is in_array(array_keys(someOtherArray)) %}
       {{ myVar }} exists within someOtherArray.
    {% else %}
       {{ myVar }} doesn't exist within someOtherArray.
    {% endif %}
{% endfor %}

Is there a way to accomplish this which I haven't seen yet?

If I need to create my own extension, how can I access myVar within the test function?

Thanks for your help!


Source: (StackOverflow)

How do I fix "Add myBundle to the asseticBundle config" symfony2 exception?

When I am trying to use the TWIG {% javascript %} tag to link to my .js file it return me with the following exception :

An exception has been thrown during the compilation of a template ("You must add CompetitiongameBundle to the assetic.bundle config to use the {% javascripts %} tag in CompetitiongameBundle:game:index.html.twig.") in "CompetitiongameBundle:game:index.html.twig".

My index.html.twig looks like :

{% javascripts 'CompetitiongameBundle/Resources/views/public/js/*'%}
    <script type="text/javascript" src="{{ asset_url }}" ></script>
{% endjavascripts %}
Hello {{ name }}!

<a rel='nofollow' href='{{ nexturl }}' >Login</a>

My Bundle is already present in the config file when I do :

php app/console config:dump-reference assetic

How can I fix this ?


Source: (StackOverflow)

Twig for loop and array with key

I use Twig and I have an array with key like this :

array[1] = "Array1"
array[2] = "Aay1"
array[3] = "Aray1"
array[8] = "Arr1"
array[9] = "Array"

And I would like to get the key (1,2,3,8,9) and the content (Array1, Aay1, Aray1, Arr1, Array) in a loop to get all value of this array.

How I can do this ?

Thank you


Source: (StackOverflow)

Add more than one parameter in Twig path

How to add more than one parameter in Twig path?
Say you have this route :

article_show:
    pattern:  /article/{slug}
    defaults: { _controller: AcmeArticleBundle:Article:show }

You can do this in your twig template :

{{ path('article_show', { 'slug': article.slug }) }}

but what if you have this in your routing file:

_files_manage:
    pattern: /files/management/project={idproject}&user={iduser}
    defaults: { _controller: AcmeTestBundle:File:manage }

It looks like they didn't cover this in their documentation.


Source: (StackOverflow)

twig: IF with multiple conditions

It seem I have problem with a twig if statement.

{%if fields | length > 0 || trans_fields | length > 0 -%}

The error is:

Unexpected token "punctuation" of value "|" ("name" expected) in 

I can't understand why this doesn't work, it's like if twig was lost with all the pipes.

I've tried this :

{% set count1 = fields | length %}
{% set count2 = trans_fields | length %}
{%if count1 > 0 || count2 > 0 -%}

but the if also fail.

Then tried this:

{% set count1 = fields | length > 0 %}
{% set count2 = trans_fields | length > 0 %}
{%if count1 || count2 -%}

And it still doesn't work, same error every time ...

So... that lead me to a really simple question: does Twig support multiple conditions IF ?


Source: (StackOverflow)

Accessing the logged-in user in a template

I'm using FOSuserbundle to get started with User registration https://github.com/FriendsOfSymfony/FOSUserBundle

I've got it registering / logging in and out. What I want to do now is grab the logged in users data and present it on every page of my site. Like "Hi username" in the header type of thing.

It seems like embedding a controller in my app/Resources/views/base.html.twig is the best way to do this http://symfony.com/doc/current/book/templating.html#embedding-controllers

So I wrote my controller to access the user profile data. What I can't figure out is how to access FOS methods in my embedded controller. So from my Acme/UserBundle/Controller/UserController.php I want to do this:

public function showAction()
{
    $user = $this->container->get('security.context')->getToken()->getUser();
    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException(
               'This user does not have access to this section.');
    }

    return $this->container->get('templating')
      ->renderResponse('FOSUserBundle:Profile:show.html.'.$this->container
      ->getParameter('fos_user.template.engine'), array('user' => $user));
}

which I grabbed from: vendor/bundles/FOS/UserBundle/Controller/ProfileController.php


Source: (StackOverflow)

How to include CSS file in Symfony 2 and Twig?

I'm playing around with Symfony 2, and I have problems including CSS and JS files in Twig template.

I have a bundle named Webs/HomeBundle. Inslide I have HomeController with indexAction that renders a twig template file:

public function indexAction()
{
    return $this->render("WebsHomeBundle:Home:index.html.twig");
}

So this is easy. Now what I want to do, is to include some CSS and JS files inside this Twig template. Template looks like this:

<!DOCTYPE html>
    <html>
        <head>  
            {% block stylesheets %}
                <link rel='nofollow' href="{{ asset('css/main.css') }}" type="text/css" rel="stylesheet" />
            {% endblock %}
        </head>
        <body>
        </body>
    </html>

The file I would like to include, main.js file is located in:

Webs/HomeController/Resources/public/css/main.css

So my question is basically, how the hell do I include simple CSS file inside Twig template?

I'm using Twig asset() function and it joust doesn't hit the right CSS path. Also, I run this command in console:

app/console assets:install web

This created a new folder, /web/bundles/webshome/... this is just linking to the src/Webs/HomeController/Resources/public/ right?

So anyway, my questions are: 1. Where do you place your "asset" files, JS, CSS, and images? Is it OK to put them in Bundle/Resources/public folder? Is that the right location for them? 2. How do you include these "asset" files in your Twig template using asset function? If they are in public folder, how can I include them?

Should I configure something else?


Source: (StackOverflow)