Using front.tpl in Drupal 7 for another Page

2019-07-16 12:12发布

问题:

Pretty straight forward question:

I have page--front.tpl and page.tpl template pages in use in a drupal 7 site. However, I'd like to use page-front.tpl on one other page. Is this possible or do I need to create another .tpl page to do this.

The site I'm working on is split into two sections, it's essentially two seperate websites that you can flip between whether your a consumer or business owner. So I want to use the front.tpl template for the home page of each site.

Cheers.

回答1:

You can add theme_preprocess_page function to your theme's template.php file and then add your template name in templates suggestions list.

function mytheme_preprocess_page(&$vars) {
    // you can perform different if statements
    // if () {...
        $template = 'page__front'; // you should replace dash sign with underscore
        $vars['theme_hook_suggestions'][] = $template;
    // }
}

EDIT

If you want to specify template name by path alias, you could write code like this:

function phptemplate_preprocess_page(&$variables) {
    if (module_exists('path')) {
        $alias = drupal_get_path_alias($_GET['q']);
        if ($alias != $_GET['q']) {
            $template = 'page_';
            foreach (explode('/', $alias) as $part) {
                $template.= "_{$part}";
                $variables['theme_hook_suggestions'][] = $template;
            }
        }
    }
}

Without this function you would have the following node template suggestions by default:

array(
    [0] => page__node
    [1] => page__node__%
    [2] => page__node__1
)

And this function would apply to your node the following new template suggestions. Example node with node/1 path and page/about alias:

array(
    [0] => page__node
    [1] => page__node__%
    [2] => page__node__1
    [3] => page__page
    [4] => page__page_about
)

So after that you can use page--page-about.tpl.php for your page.

If you want to apply page--front.tpl.php to your let's say node/15, then in this function you can add if statement.

function phptemplate_preprocess_page(&$variables) {
    if (module_exists('path')) {
        $alias = drupal_get_path_alias($_GET['q']);
        if ($alias != $_GET['q']) {
            $template = 'page_';
            foreach (explode('/', $alias) as $part) {
                $template.= "_{$part}";
                $variables['theme_hook_suggestions'][] = $template;
            }
        }
    }

    if ($_GET['q'] == 'node/15') {
        $variables['theme_hook_suggestions'][] = 'page__front';
    }
}

This would give you the following template suggestions:

array(
    [0] => page__node
    [1] => page__node__%
    [2] => page__node__1
    [3] => page__page
    [4] => page__page_about
    [5] => page__front
)

The highest index - the highest template priority.