问题描述:

I have a site with a fairly complex structure of Smarty templates. For this question, suppose I have an outer template which includes (with {include}) one or more inner templates that are optionally included, depending on the data being displayed:

Outer Template (with <html>, <head>, and <body> tags)

- Inner Template A (various content)

- Inner Template B (more content)

Sometimes, one of these inner templates needs to reference additional CSS files. I would prefer to have these within my <head> tag, for efficiency and to avoid FOUC. Is it possible to set some variable from Inner Template A that adds the appropriate <link> tag to <head> within Outer Template?

I was able to find someone who created a module to do something similar, but I don't know how I would set the necessary variables from the template to make it work in my case. I am using Smarty 3.

网友答案:

I had a similar issue some time ago. My solution is maybe dirty but maybe it could help you.

$css = '<link rel="stylesheet" type="text/css" href="/css/file.css">';
$smarty->registerFilter('output',create_function('$output','return preg_replace(\'/(<\/head>)/i\',\''.$css.'$1\',$output,1);'));

If you wrap this in a function, you can simply add css to your head section from everywhere.

网友答案:

Idea 1:

Wrap the same logic around the style sheet in your head that you use for displaying template A or B.

Idea 2:

Template 1 (Top Level):

<link rel="stylesheet" type="text/css" href="whatevs1">
{block name="childStyles"}
{/block}

Template 2 (Child Template):

{block name="childStyles"}
<link rel="stylesheet" type="text/css" href="whatevs2">
{/block}

A side note:

I understand the want to be W3 compliant using includes for stylesheets in HEAD but including them within the body wont break your html, even in IE7...

网友答案:

I encountered a similar obstacle a few years ago. Since smarty templates are almost all the time filled with php code, my solution is just declaring a special variable/array for this purpose in php, then looping through the array in your head template / outer template.

Example:

$your_special_css = array('css1.css', 'css2.css');

Somewhere else in your code...

$your_special_css[] = 'css3.css';

...and then give it to the template:

$your_smarty_template->assign('your_css', $your_special_css);

Then your outer template would look like this:

<head>
 ...
{foreach $your_css as $css}
    <link rel="stylesheet" type="text/css" href="/css/{$css}">
{/foreach}
...
</head>

Same works for jscript-files, too.

相关阅读:
Top