php-mvc icon indicating copy to clipboard operation
php-mvc copied to clipboard

Accessing twig arguments from a view when template is passed as a variable

Open pf-tech opened this issue 3 years ago • 3 comments

Hello,

Goal: use View::renderTemplate ( default/index.html, [ templateVars, THE TEMPLATE FILE LOCATION ]); Render the TEMPLATE and utilize Twig's {{ }} for the templateVars

Issue: Unable to access the templateVars from the View when TEMPLATE is a variable {% include(TEMPLATE-AS-A-VARIABLE) %} included on the page and not {% include('path/to/actualFileName.html') %}

Reason: I'm trying to have a static page like base.html change out the contents dynamically within one action->method, instead of changing out the render template each time. I know that if I call the template from within the view::renderTemplate the Twig variables work fine.


I've tried a few things, such as adding a new render method in Core/View to return the values instead of echoing them out per a closed issue I found in your closed issues log. I've also tried several of the items on Twig's documentation, such as accessing the vars as a macro or trying to extend the include. I've tooled around on StackOverflow too, but so far, I haven't figured out how to do it.

Code: //Controller, Action => index View::renderTemplate(\App\Config::PF_ADMIN_DIR . '/index.html', [ 'loopofnumbers' => $ARRAY_OF_NUMBERS, 'passed_template' => \App\Config::ADMIN_DIR . $this->template, <--DYNAMIC TEMPLATE ]);

//Views, base.html

pf-tech avatar Jan 27 '22 18:01 pf-tech

I'm afraid I don't fully understand what you're trying to do, but when you use include in Twig (documentation here), you can pass variables to the included file:

{{ include('template.html', {foo: 'bar'}) }}

Is that what you meant?

daveh avatar Jan 28 '22 10:01 daveh

Not quite. Bar would need to be a variable as well. {foo: {{bar}} }}

Basically, Twig seems to not evaluate the template when it is dynamic and coming from the controller action instead of being called as part of the render line.

View::renderTemplate(\App\Config::PF_ADMIN_DIR . $this->template_name, //<-- works with a dynamic template name (I don't want this one) View::getTemplate(\App\Config::PF_ADMIN_DIR . '/index.html', [ template_name => $templat_name as a var] //<--doesn't work (I want this one to take the other passed arguments, along with the template name, and render them, but it doesn't see the other variables passed to the template.)

pf-tech avatar Jan 28 '22 15:01 pf-tech

Ah ok - I'm not sure of a way you can do that I'm afraid. Perhaps if you ask a question in a Twig forum like this one someone might be able to help.

daveh avatar Jan 30 '22 12:01 daveh