V
V
Vyacheslav Barsukov2015-06-17 04:46:50
symfony
Vyacheslav Barsukov, 2015-06-17 04:46:50

How to display the output of a class method in Twig?

There are 2 databases: salon: id name
city_id
city: id, name

{% for salonTables in salonTable %}
{ salonTables.name|escape }}
{{ salonTables.cityId|escape }}
{% endfor %}

I get the name of the city like this
\AppBundle\Entity\City::getNameFromId(salonTables.cityId)
How do you handle city name in twig? Type design
{% for salonTables in salonTable %}
{ salonTables.name|escape }}
{{ \AppBundle\Entity\City::getNameFromId(salonTables.cityId) }}
{% endfor %}

Returns error
Unexpected character "\" in salon/index.html.twig at line 151

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
jaxel, 2015-06-17
@slavabars

As far as I know, you can't use static class methods in Twig.
I can offer 2 options:
1) Create your own extension for twig, and use it on a variable as a filter
2) Pass an instance of the City class to the template and use the method already from it.
{{ city.nameFromId(salonTables.cityId) }}

A
Alexey Pavlov, 2015-06-17
@lexxpavlov

You can run a static class method by calling it through an object of this class:

class Test {
    private $x = 10;

    public static function getSTatic() {
        return 'static';
    }
    public function getNormal() {
        return 'normal ' . $this->x;
    }
}

Now in the controller you need to create an object of this class and pass it to the template:
{{ test.normal }}
{{ test.static }}

In your case, you can call like this: {{ city.nameFromId(salonTables.cityId)) }}where city is an object of class City.
But in general, you are better off redoing everything completely. Based on the Symfony tag in the question, you are using the Symfony2 framework. Then you shouldn't write static methods for getting records at all, use the doctrine.
1) It is incorrect to access the database in the template, correctly prepare all the necessary data in the controller and pass them to the template:
class SalonController extends Controller
{
    /**
     * @Route("/salon/{id}")
     * @Template
     */
    public function salonAction($id)
    {
        $salons = $this->getDoctrine()->getRepository('AppBundle:City')->findBy(array('cityId' => $id));

        return array('salons' => $salons);
    }
}

2) the twig escapes the output itself, it is not necessary to do |escape
3) you should not add the word table to the name of the entity, it is much better to write them like this:
{% for salon in salons %}
{ salon.name }}
{{ salon.cityId }}
{% endfor %}

K
keltanas, 2015-06-17
@keltanas

\AppBundle\Entity\City::getNameFromId(salonTables.cityId)

Something tells me that he is already using the doctrine ... as an AR ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question