You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jinja2渲染XML格式NETCONF配置模板时变量未填充问题咨询

问题根因

Jinja2的Template.render()方法默认接收关键字参数完成变量映射,你当前直接将字典对象作为位置参数传入render方法,模板无法识别字典内的键为顶层变量,因此无法完成值填充。

修复方案

推荐使用字典拆包的方式传入参数,仅需修改渲染一行代码即可:
将原代码中的
netconf_payload = netconf_template.render(netconf_data)
修改为
netconf_payload = netconf_template.render(**netconf_data)

额外检查项

  • 确认new_config.j2模板中的变量均使用{{ 变量名 }}格式包裹,且变量名与netconf_data字典中的键完全一致(大小写敏感)
  • 确认模板文件路径正确,读取的内容为你编写的Jinja2模板而非空文件或其他文件内容

修复后完整代码

from ncclient import manager
from jinja2 import Template

# netconf Connection Manager
# netconf_connection = manager.connect(host='1.1.1.1',
#                     port=830,
#                     username='admin',
#                     password='admin',
#                     device_params={'name': 'iosxr'},
#                     hostkey_verify=False,
#                     look_for_keys=False)

netconf_data = {
    "carrier_vlan": 101,
    "customer_vlan": 1000,
    "HUB_WAN1_PUBLIC_IP": "10.10.10.10",
    "customer": "FirstNetConfTest",
    "PRIMARY_TRANSIT": "11.11.11.11",
    "neighbor_IP": "11.11.11.12",
    "Location": "LAX"
    }

netconf_file = open('templates/new_config.j2').read()
netconf_template = Template(netconf_file)
# 仅修改此处,添加**对字典拆包
netconf_payload = netconf_template.render(**netconf_data)

print(netconf_payload)

内容的提问来源于stack exchange,提问作者Texia Plazaola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:24:02