简体   繁体   中英

Twig Runtime Error: Impossible to invoke a method (“test”) on a string variable

I have the following twig template (the code is in the same file):

{% macro renderJob(fields) %}
    // renders the job UI block, but I've removed it for simplicity
    Hello world.
{% endmacro %}
{% block _jobs_widget %}
    <div id="jobsContainer">
        {% for fields in form.children %}
            {% dump fields %}
            {{ _self.renderJob(fields) }}
        {% endfor %}
    </div>
{% endblock %}

For some reason, after upgrading to twig/twig = v2.1.0 I'm receiving the follwing error:

Impossible to invoke a method ("renderJob") on a string variable ("@AppBundle/Jobs/form/job.html.twig").

I have been trying to figure out what's causing this without any luck. This used to work just fine in 1.3.x . The fields variable contains the proper data, but it appears it can't pass it to the renderJob macro or it can't find the macro (which is kind of odd)?

Have you tried the following ?

{% import _self as renderJobMacro %}

{% macro renderJob(fields) %}
    // renders the job UI block, but I've removed it for simplicity
    Hello world.
{% endmacro %}

{% block _jobs_widget %}
    <div id="jobsContainer">
        {% for fields in form.children %}
            {{ renderJobMacro.renderJob(fields) }}
        {% endfor %}
    </div>
{% endblock %}

No clue why it worked before, but you still need to import the macro before you can use it:

{% macro renderJob(fields) %}
    // renders the job UI block, but I've removed it for simplicity
    Hello world.
{% endmacro %}

{% import _self as macro %}

{% block _jobs_widget %}
    <div id="jobsContainer">
        {% for fields in form.children %}
            {% dump fields %}
            {{ macro.renderJob(fields) }}
        {% endfor %}
    </div>
{% endblock %}

fiddle

I think _self is depricated from twigg 2.0, May be you need to check without _self .

Check {{ renderJob(fields) }} instead of {{ _self.renderJob(fields) }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM