Drupal 7:从钩子菜单打印主题,性能良好



我正在自定义路由的钩子菜单中工作,如下所示:

function mymodule_menu() {
$items = [];
$items['myroute/%'] = array(
'page callback'     => 'my_callback',
'page arguments'     => array(1),
'access arguments'  => array('access content'),
);
return $items;
}

在theme_hook中,我添加了一个新的模板功能,如下所示:

function mymodule_theme($existing, $type, $theme, $path) {
$default = array(
'path' => drupal_get_path('module', 'mymodule') . '/templates',
'variables' => array(),
);
return array(
'product_tile' => array_merge($default, array(
'template' => 'product-tile',
)),
);
}

我创建了一个名为"product-tile.tpl.php"的模板文件,该文件适用于所有情况,并且是部分模板。

在回调函数中,我需要返回一个特定的 .tpl.php 模板,如下所示:

function my_callback($parameter) {
$template_data = 'lorem ipsum';
$output = theme('product_tile', array('content' => $template_data ));
echo ($output);
}

关键是:"theme()"函数渲染数据的时间太长,它不仅渲染模板,而且渲染整个 html 结构,这是不需要的,也不是模板的一部分。

例如:模板是:

<div id="my structure></div>

但是当我得到对'/myroute/myparameter的响应时,它不是打印我的模板,而是像这样打印所有html结构:

<html>
<body>......lots of stuff here +js +css + all drupal stuff
<div id="my structure></div>
</body>
</html>

并且需要大量时间打印(例如 10 秒或更长时间)。

我试图使用 cache_get 和 cache_set 来缓存它,但奇怪的事情正在发生,比如随机的空响应。

有谁知道在 drupal 7 的钩子菜单中打印部分模板的高性能方法?这种方式非常慢。

提前致谢

您的自定义路由映射到page callback,该函数必须返回要在页面内呈现的内容才能交付(而不仅仅是打印某些内容)。

此内容可以是:

  • 一个 HTML 字符串
  • Drupal 渲染数组
  • 或菜单状态代码(MENU_ACCESS_DENIEDMENU_NOT_FOUND等)

该内容(如果不是 HTML 字符串,则一旦呈现)就是您在传递给活动主题的page.tpl.php$content$page['content']变量中实际获得的内容。

现在,您的问题可能只是由使用此模板引起的(例如,如果它包含繁重的PHP或糟糕的实现,无论出于何种原因),但它可能是完全不同的:

  • "theme()"函数渲染数据的时间太长

    交付该页面所需的时间并不一定意味着它是由此主题功能引起的。您可以检查呈现该特定模板的实际时间 - 而不是整个 HTML 页面 - 可能不是10 秒:

    $start = microtime(true);
    $output = theme('product_tile', array('content' => 'lorem ipsum'));
    $end = microtime(true);
    $time = $end - $start;
    # dpm() is brought by devel module
    dpm('product_tile rendering: ' . $time . 'sec.');
    

    由于渲染自定义模板时涉及一些繁重的 drupal 钩子和预处理函数,页面交付可能会很长,但也可能是渲染页面其他区域(侧边栏、页眉、页脚等)的成本。

  • 当我收到对/myroute/myparameter 的响应时,它不会打印我的模板,而是打印所有 html

    如上所述,路由路径的响应是一个完整的 HTML 页面,其中包含相应菜单项中定义的"页面回调"的输出作为"内容"。drupal 页面回调的预期行为正是返回要在该页面上显示的内容,加载完整的 HTML 页面。这就是为什么需要return语句的原因(如果不是,请不要假设任何事情),不要在页面回调中使用printecho函数,要查看变量的内容,请使用调试函数,例如dpm):

    function my_callback($parameter) {
    $template_data = 'lorem ipsum';
    $output = theme('product_tile', array('content' => $template_data ));
    # debug the output of 'product_tile'
    dpm($output);
    # return what should be displayed on that page
    return output;
    }
    

最新更新