Component requires javascript, what's the best way to include it
- mishak
- Member | 94
I have component, some functionality is in javascript.
I would like to have list of all scripts before template is rendered eg.: for compression and merge (same for styles).
So I added to presenter function addScript($file) that store information about included scripts. In component I wait until presenter is assigned and then I call this function. In @layout.latte all scripts are added. But that to work i have to access component before template rendering. Because presenter is assigned somewhere after layout template is rendered.
My hack is this:
<?php
function renderDefault()
{
$this['componentXYZ'];
}
?>
Do you have suggestions how to do it better?
Also I would like to have macro in template for registering scripts and styles for same reason.
- norbe
- Backer | 405
You can wrap part of your template into macro capture
.
Example:
<html>
<head>
{capture $layout}
</head>
{control component XYZ}
{/capture}
{control js} // include JS files into template
{!$layout}
</html>
But before you start implementation of this solusion, I have warn you. Every page with different components will probably have different final (merged) js file. All this final files could be almost the same and this parts must to be downloaded again and again (no browser cache can be used for it).
I think better solution is to merge all files that you can need on all site. Example:
<html>
<head>
{control 'a.js','b.js', ... ,'z.js'}
</head>
{control component XYZ}
</html>
Now the browser can use cache much better. And additionally its more easier to manage dependencies of js files.
Last edited by norbe (2011-11-22 22:46)
- mishak
- Member | 94
Thanks, I have not thought about solving it with printing scripts last. Are
there some side-effects to using capture
macro? Except obvious one
more ob_start/end.
Packing everything in one file is one solution but I was thinking about splitting them to compressed groups smartly by evaluating usage data. My target is smart solution without maintenance.
Last edited by mishak (2011-11-23 00:29)