Chapter 9. Config Files

Config files are handy for designers to manage global template variables from one file. One example is template colors. Normally if you wanted to change the color scheme of an application, you would have to go through each and every template file and change the colors. With a config file, the colors can be kept in one place, and only one file needs to be updated.

組態檔讓設計者可以很方便的管理從檔案取出的全域變數,例如樣版的顏色,一般而言 ,如果你要改變某個應用程式內顏色的組合,你就必須開啟每個樣版檔案且改變顏色。如果使用 組態檔案的話,這些顏色設定可以放在一個檔案中,如此一來只需更新這個檔案即可。

Example 9-1. 組態檔案文法範例

# global variables
pageTitle = "Main Menu"
bodyBgColor = #000000
tableBgColor = #000000
rowBgColor = #00ff00

[Customer]
pageTitle = "Customer Info"

[Login]
pageTitle = "Login"
focus = "username"
Intro = """This is a value that spans more
           than one line. you must enclose
           it in triple quotes."""

# hidden section
[.Database]
host=my.example.com
db=ADDRESSBOOK
user=php-user
pass=foobar

Values of config file variables can be in quotes, but not necessary. You can use either single or double quotes. If you have a value that spans more than one line, enclose the entire value with triple quotes ("""). You can put comments into config files by any syntax that is not a valid config file syntax. We recommend using a # (hash) at the beginning of the line.

組態檔中的變數可以用單引號或雙引號括起來,但不是必須的。如果你有一個變數值多 於一行的話,可以用三個引號括起來 (""")。你可以使用不是組態檔正式文法的語法將註解加入 組態檔,我們推薦在每一行的開頭使用 # (hash)。

This config file example has two sections. Section names are enclosed in brackets []. Section names can be arbitrary strings not containing [ or ] symbols. The four variables at the top are global variables, or variables not within a section. These variables are always loaded from the config file. If a particular section is loaded, then the global variables and the variables from that section are also loaded. If a variable exists both as a global and in a section, the section variable is used. If you name two variables the same within a section, the last one will be used.

範例中的組態檔分成兩區塊,兩區塊的名稱用 [] 括弧包住,區塊的名稱可以是 [] 符號之外的任何字元字串。檔案頂端的四個變數是全域變數,或者說是非區域變數。這些名稱 的變數總是會從組態檔下載到檔案,如果現在假設載入了特別的區塊,全域變數與特殊區塊內的 變數都會被載入。如果有個變數同時存在於全域變數的區塊與特殊的區塊,則會使用特殊區塊內 變數的值,如果在同一個區塊你對同一個變數名稱設定兩次,則會使用最後設定的值。

Config files are loaded into templates with the built-in function config_load.

組態檔是藉由內建函式 config_load 載入到樣版的。

You can hide variables or entire sections by prepending the variable name or section name with a period. This is useful if your application reads the config files and gets sensitive data from them that the template engine does not need. If you have third parties doing template editing, you can be certain that they cannot read sensitive data from the config file by loading it into the template.

你可以在變數名稱或區塊名稱前面加上.符號以隱藏變數或整個區塊,此將有助於當你 的應用程式讀取組態檔,但組態檔中有些敏感資料是你的樣版引擎用不到的。如果你與第三方人 員合作編輯樣版檔案,這麼一來你可以確定他們不會因為將組態檔載入到樣版檔中而讀取到敏感 資料。