php - Defer execution/completion in Twig -
i using twig separately symfony2 framework, smaller rolled suit (perceived) needs better. part of framework asset management library manages js/css dependencies, , after preprocessing, combining, minifying, gzipping, outputs appropriate <link>
, <script>
tags placed in <head>
or in bottom of <body>
.
the asset helper has 3 public functions: require_asset($asset)
, render_head()
, render_bottom()
. first 1 used sparingly throughout different template parts (i want keep loading of assets outside application logic, hence inside twig templates). 2 others need called after assets have been required, , (after asset manager thing) return appropriate , tags placed in template.
all normal templates extend base template:
base.twig:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>{{ title }}</title> <!--[if lt ie 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> {{ assets.headassets }} </head> </body> {% block body %} {% endblock %} {{ assets.bottomassets }} <body> </html>
here {{ assets.headassets }}
, {{ assets.bottomassets }}
calls through declared twig global variable assets
aforementioned render_head()
, render_bottom()
methods;
in instance, base template extended test.twig:
{% extends "base.twig" %} {% import "forms.twig" forms %} {% block body %} {{ assets.requires('formtest.css') }} {{ assets.requires('testscript.js') }} <form method="post"> {{ forms.form(form) }} <input type="submit"/> </form> {% endblock %}
here, {{ assets.requires('formtest.css') }}
, {{ assets.requires('testscript.js') }}
instruct assets helper include css , js required template through calling require_asset($asset)
.
normally, if done outside twig, output functions called last, after needed assets have been required. works expected.
the problem running has order of execution of these functions twig template. since base.twig called first, , contains calls output functions, these called before requirement made extending templates or included blocks/macros. because of result empty , not take account these new requirements.
one way have though of solve problem, calculate outputs after twig has returned rendering, , replace them in returned result. works, feel not elegant enough.
i wondering if there way postpone execution of {{ assets.headassets }}
, {{ assets.bottomassets }}
until twig done else. there way me achieve this?
i think work:
base.twig
{% set bodycontent %} {% block body %}{% endblock body %} {% endset %} <!doctype html> <html> <head> <meta charset="utf-8"> <title>{{ title }}</title> <!--[if lt ie 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> {{ assets.headassets }} </head> </body> {{ bodycontent }} {{ assets.bottomassets }} <body> </html>
other files can unmodified.
as can see, block body
calls first in base.twig
template, assets required when execution came {{ assets.headassets }}
call.
Comments
Post a Comment