9
我正在嘗試編寫一個小腳本,用於自動執行一些我需要編寫的PHP樣板文件。它應該將字符串code
的副本寫入輸出文件,併爲fields
列表中的每個字典填寫各種替換字段。字符串格式化時,字段名稱中出現意外的'{''
不過,我發現了錯誤:
Traceback (most recent call last):
File "writefields.py", line 43, in <module>
formatted = code.format(**field)
ValueError: unexpected '{' in field name
據我所知,還有無論是在替換字段或應引起問題類型的字典沒有多餘的括號,所以任何幫助會不勝感激。
code = '''
// {label}
add_filter('submit_job_form_fields', 'frontend_add_{fieldname}_field');
function frontend_add_{fieldname}_field($fields) {
$fields['job']['job_{fieldname}'] = array(
'label' => __('{label}', 'job_manager'),
'type' => 'text',
'required' => {required},
'priority' => 7,
'placeholder' => '{placeholder}'
);
return $fields;
}
add_filter('job_manager_job_listing_data_fields', 'admin_add_{fieldname}_field');
function admin_add_{fieldname}_field($fields) {
$fields['_job_{fieldname}'] = array(
'label' => __('{label}', 'job_manager'),
'type' => 'text',
'placeholder' => '{placeholder}',
'description' => ''
);
return $fields;
}
'''
fields = [
{
'fieldname': 'salary',
'label': 'Salary ($)',
'required': 'true',
'placeholder': 'e.g. 20000',
},
{
'fieldname': 'test',
'label': 'Test Field',
'required': 'true',
'placeholder': '',
}
]
with open('field-out.txt', 'w') as f:
for field in fields:
formatted = code.format(**field)
f.write(formatted)
f.write('\n')