【问题标题】:Replacing variables in a dictionaryand using doc.render替换字典中的变量并使用 doc.render
【发布时间】:2021-03-31 16:37:35
【问题描述】:

我正在使用 doc.render 编辑模板文档,并用我的 python 代码中的变量替换它们。但是,如果变量是一个数字,我不希望它被渲染,而是用“”代替。我的问题是如何区分上下文和 doc.render 以仅替换某些变量。 目前我是这样做的

doc = DocxTemplate('Template.docx')
            context = {
                'acc':acceleration,
                'dpt':depth
            }
doc.render(context)

因此,如果加速度是一个数字,我希望模板中的 acc 为 '',其余部分正常工作

【问题讨论】:

    标签: python docx editing


    【解决方案1】:

    据我了解 docxtpl 包,它与 jinja2 包一起工作。所以选项是利用 jinja2 的力量和提供的{% if users %} 条件。

    我会在 python 中完成大部分逻辑,并且只使用模板库来填充和渲染模板。意思是,在python中对字典进行值转换,然后将这个字典推送到render方法。

    context = {'acc':acceleration,
               'dpt':depth}
    
    # if the numeric values are given as strings
    context_ = {k: v if not v.isnumeric() else "" for k,v in context.items()}
    # if the numeric values are as numeric
    context_ = {k: v if not any([isinstance(v, int), isinstance(v, float)]) else "" for k,v in context.items()}
    doc.render(context_)
    

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 2021-05-15
      • 2016-12-15
      • 2020-02-29
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      相关资源
      最近更新 更多