問題描述
前提條件:來自自定義 PHP 應用程序 (使用 symfony,zend 等) 的世界,對於我來説,以原始 wordpress 主題完成的方式分離模板感覺不自然。例如頁面的頂部位於標題中,位於 「索引,頁面…」 中,底部部分位於頁腳中。
當前結構示例:index.php
[include header]
... main content...
[include footer]
和 header.php
<html>
<head>
....
</head>
<body>
.....
和 footer.php
.....
</body>
</html>
我更習慣於具有佈局的結構,並在其中包含其他 (部分) 模板。示例:index.php 模板
<html>
<head> [include header] </head>
<body>
[include body] [include footer]
</body>
</html>
所以我試圖想到原始 wordpress 模板結構的優勢。
問題:與上述第二個例子相比,ORIGINAL wordpress 模板結構的優點是什麼?
最佳解決方案
首先,如 @Toscho 所暗示的,get_header()和 get_footer()模板標籤分別僅包括名為 header.php 和 footer.php 的文件。在模板文件中調用兩個模板標籤,您可以以任何方式將模板文件 (index.php) 和模板部件文件 (header.php,footer.php) 之間的內容分開。所以 WordPress 當然可以適應你的後一個例子。
也就是説,實際功率在標準中,”WordPress” 分離內容的方法來源於 WordPress Template Hierarchy 。在 WordPress 中,index.php 文件實際上是最後使用的模板文件。當沒有找到其他的 more-specific 模板文件時,它是默認的後備模板文件:
由於根據當前的上下文”WordPress” 的標記方法,將使用 7(主) 到 16(次) 模板文件中的任何一個 (並且僅用於公開分發的主題; custom-designed 主題可以有任意數量的模板文件) 分離最小化重複代碼的數量。
假設您要將您的 doctype 從過渡到更改 (嚴格 (或您想移動到 HTML5)),或者您想要更改站點頁腳中的版權聲明。使用”WordPress” 標記分離方法,您可以在一個文件中進行更改。使用後一種內容分離方法,您可以將這些更改改為七到十六 (或更多) 次。
Edit
我想到這個問題會出現:
I want to hear your opinion concerning following situation. Let’s say we need to include “og tags (Open Graph meta tags)” and they have different format for “index”, “single.php” “page” “archive” templates. If we have a structure like “original wp theme structure” then we have to use conditional statements(if..else) in the “header.php” file, right ? And I think everybody agrees less “conditional statements” better performance per request, right ?
我們有幾個選擇:
-
直接在
header.php內使用 PHP 查詢條件 -
在回調中使用 PHP 查詢條件,掛接到
wp_head(或wp_enqueue_scripts等) -
使用
get_header( $context ),其中$context基於模板層次結構,如果找到,將包含header-$context.php,如果未找到,則為header.php。
但是,多個選項並沒有真正解決您關於性能問題的根本問題。就個人而言,我認為性能命中可以忽略不計,因為所有查詢條件都被緩存為查詢對象緩存的一部分。所以稱他們真的不應該發生任何有意義的表現。
次佳解決方案
沒有矛盾,你可以同時使用。
例子
<!doctype html>
<html <?php language_attributes(); ?>>
<head>
<?php get_header(); ?>
</head>
<body>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php get_footer(); ?>
</body>
</html>
WordPress 系統的優點是:您可以根據需要自由構建模板。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。
