如何遍历字典和文件树?我想将带有.j2后缀(关键字)的模板文件递归到目标位置(值),还应该重命名基本名称(删除.j2后缀)。它是一个完美的用例。不幸的是,ansible不适用于复杂的数据结构。
输入:
public GameObject scoretext;
public GameObject itemlefttext;
public GameObject finalScore;
public static float score = 0;
public GameObject winPanel;
private void Start()
{
scoretext.GetComponent<Text>().text = "0";
setscore(0);
}
private void Update()
{
itemlefttext.GetComponent<Text>().text = "" + GameObject.FindGameObjectsWithTag("draggableobject").Length;
if (GameObject.FindGameObjectsWithTag("draggableobject").Length == 0)
{
winPanel.SetActive(true);
}
}
public void setscore(float scoretoadd)
{
score += scoretoadd;
scoretext.GetComponent<Text>().text = score.ToString("F0");
finalScore.GetComponent<Text>().text = score.ToString("F0");
}
我的尝试:
{% for brand in brands %}
{% if brand.product %}
<!-- Displays brand -->
{% endif %}
{% endfor %}
我知道在游戏中使用jinja不好,如果可能的话,我想避免使用它。另外,输入数据结构也不应更改。
感谢
答案 0 :(得分:1)
如果我了解您要执行的操作,那么我认为有一个相当简单的解决方案。如果您编写一个名为template_files.yml
的任务文件:
---
- name: render templates to dest_dir
loop: "{{ query('filetree', src_dir) }}"
# we need this to avoid conflicts with the "item" variable in
# the calling playbook.
loop_control:
loop_var: template
when: template.src.endswith('.j2')
template:
src: "{{ template.src }}"
dest: "{{ dest_dir }}/{{ (template.src|basename)[:-3] }}"
然后您可以编写这样的剧本:
---
- hosts: localhost
gather_facts: false
vars:
applications:
application1:
svcpaths:
localfolder/bardir1: /tmp/remotefolder/bardir1
localfolder/bardir2: /tmp/remotefolder/bardir2
localfolder/bardir3: /tmp/remotefolder/bardir3
application2:
svcpaths:
localfolder/bardir5: /tmp/remotefolder/bardir5
localfolder/bardir6: /tmp/remotefolder/bardir6
tasks:
# generate a list of {key: src, value: destination}
# dictionaries from your data structure.
- set_fact:
templates: "{{ templates|default([]) + item|dict2items }}"
loop: "{{ applications|json_query('*.svcpaths')}}"
# show what the generated variable looks like
- debug:
var: templates
# template all the things
- include_tasks: template_files.yml
loop: "{{ templates }}"
vars:
src_dir: "{{ item.key }}"
dest_dir: "{{ item.value }}"
鉴于我有一组本地文件,如下所示:
localfolder/bardir1/example.txt.j2
localfolder/bardir2/example.txt.j2
localfolder/bardir3/example.txt.j2
localfolder/bardir5/example.txt.j2
localfolder/bardir6/example.txt.j2
运行剧本会导致:
/tmp/remotefolder/bardir6/example.txt
/tmp/remotefolder/bardir5/example.txt
/tmp/remotefolder/bardir3/example.txt
/tmp/remotefolder/bardir2/example.txt
/tmp/remotefolder/bardir1/example.txt
我认为这可能比您正在使用的基于Jinja模板的解决方案更易于阅读和理解。