2017-03-07 70 views
0

我有一堆YAML文件在一個配置文件夾和模板文件夾中的一堆模板。我使用的用例是基於yaml配置和模板生成文本文件。我想看看是否可以使用python誘惑引擎來解決這個問題。使用模板引擎生成代碼(文本)

我看到模板引擎在Web開發環境中使用。我使用的用例非常相似(但不相同)。我想生成一些文本。它不需要顯示在網頁上。相反,它應該只生成一個文本文件。

例 輸入: config文件夾:配置/ yaml1,配置/ yaml2,配置/ yaml3 .. 模板:模板/模板1,模板/模板2,template3。

輸出

scripts/script1, script2, script3 

腳本的數=模板數

有2種類型的模板

一說是直接的/直接替代實施例

YAML1: 
    Titles:4 
    SubTitles:10 
Template1: 
Number of Titles {Titles} where as Number of Subtitles is {SubTitles} 

其他模板是嵌套的。基本上模板需要被環形基於YAML實施例:

YAML2: 
     Book: "The Choice of using Choice" 
      Author: "Unknown1" 
     Book: "Chasing Choices" 
      Author:"Known2" 

Template2 
Here are all the Books with Author Info 
The author of the {Book} is {Author} 

預期輸出是具有標題4的

數,其中作爲字幕的數量是10 所述的選擇的作者單個文本文件使用選擇是未知1 追逐選擇的作者是已知的2

有人可以發佈我在正確的方向嗎?

回答

0

你可以用正則表達式和搜索/替換來做到這一點。您可以將函數而不是字符串傳遞給re.sub函數。當然,這依賴於擁有有效YAML:

 
YAML1: 
    Titles: 4 
    # ^need space here 
    SubTitles: 10 
Template1: 
    Number of Titles {Titles} where as Number of Subtitles is {SubTitles} 
    # Need indentation here 

的Python代碼應該是這樣的:

import re 
import yaml 

# Match either {var}, {{, or }} 
TEMPLATE_CODE = re.compile(r'\{(\w+)\}|\{\{|\}\}') 

def expand(tmpl, namespace): 
    print(namespace) 
    def repl(m): 
     name = m.group(1) 
     if name: 
      # Matched {var} 
      return str(namespace[name]) 
     # matched {{ or }} 
     return m.group(0)[0] 
    return TEMPLATE_CODE.sub(repl, tmpl) 

def expand_file(path): 
    with open(path) as fp: 
     data = yaml.safe_load(fp) 
    print(expand(data['Template1'], data['YAML1'])) 

而這裏的輸出:當然

 
Number of Titles 4 where as Number of Subtitles is 10 

有,很多方法可以讓這個更復雜,比如使用合適的模板引擎。

+0

我正在尋找一個更簡單的解決方案,如使用像獵豹這樣誘人的引擎。我想知道如果有人能指出我的方向 – pmv

+0

@pmv:爲什麼這是錯誤的方向?如果你已經知道你想使用的模板引擎(獵豹),那麼爲什麼不直接使用它? –

+0

我正在考慮使用模板引擎來解決問題。我專門尋找一個僞代碼 – pmv