我正在使用Jinja2生成C代码。
特别是我想输出一个矩阵静态初始化器。
我可以做到,但是由于元素长度的差异很大,结果远不是很漂亮(显然,编译器不在乎)。
使用制表符可以缓解但不能解决问题。
假设我有类似的东西:
values = OrderedDict([
('STATE', {
'type': 'POWER',
'sethw': 'set_power'
}),
('REASON', {
'type': 'POWER',
'label': 'Wakeup_reason'
}),
('EN_MB_PSU', {
'type': 'RAIL',
'sethw': 'set_rail'
}),
('EN_3V3_MB_PSU', {
'type': 'RAIL',
'sethw': 'set_rail'
}),
])
模板片段为:
Value_s Values_table[] = {
/* id\t\tvalue\ttype\tlabel\t\tsubscribers\t\tset_hw */
{% for n,v in values.items() %}
{% set tag = v.type + '_' + n %}
{% if v.label is defined %}{% set lbl = v.label %}{% else %}{% set lbl = tag %}{% endif %}
{% if v.value is defined %}{% set val = v.value %}{% else %}{% set val = 0 %}{% endif %}
{% if v.sethw is defined %}{% set sth = v.sethw %}{% else %}{% set sth = "NULL" %}{% endif %}
{ {{tag}},\t{{'%d' % val}}\t{{v.type}},\t"{{lbl}}",\tSETLINK({{tag}}),\t{{sth}} },
{% endfor %}
{ 0 }
};
实际输出为:
Value_s Values_table[] = {
/* id value type label subscribers set_hw */
{ POWER_STATE, 0 POWER, "POWER_STATE", SETLINK(POWER_STATE), set_power },
{ POWER_REASON, 0 POWER, "Wakeup_reason", SETLINK(POWER_REASON), NULL },
{ RAIL_EN_MB_PSU, 0 RAIL, "RAIL_EN_MB_PSU", SETLINK(RAIL_EN_MB_PSU), set_rail },
{ RAIL_EN_3V3_MB_PSU, 0 RAIL, "RAIL_EN_3V3_MB_PSU", SETLINK(RAIL_EN_3V3_MB_PSU), set_rail },
{ 0 }
};
...而所需的结果将是:
Value_s Values_table[] = {
/* id value type label subscribers set_hw */
{ POWER_STATE, 0 POWER, "POWER_STATE", SETLINK(POWER_STATE), set_power },
{ POWER_REASON, 0 POWER, "Wakeup_reason", SETLINK(POWER_REASON), NULL },
{ RAIL_EN_MB_PSU, 0 RAIL, "RAIL_EN_MB_PSU", SETLINK(RAIL_EN_MB_PSU), set_rail },
{ RAIL_EN_3V3_MB_PSU, 0 RAIL, "RAIL_EN_3V3_MB_PSU", SETLINK(RAIL_EN_3V3_MB_PSU), set_rail },
{ 0 }
};