MediaWiki信息框模板如何实现变量为空时隐藏对应表格行
实现方案
需要先确保你的Wiki站点已启用ParserFunctions扩展,绝大多数公开Wiki站点默认预装该扩展,如果条件语法不生效联系站点运维开启即可。具体实现逻辑如下:
- 所有模板参数补充默认空值:将原有
{{{参数名}}}的写法统一修改为{{{参数名|}}},避免参数未传入时直接输出参数源码,导致条件判断失效。 - 使用
#if条件函数包裹需要条件显示的整行表格代码,语法为{{#if: 待判断的参数 | 参数非空时渲染的内容 }},参数为空时函数不返回任何内容,对应表格行就会自动隐藏。
你原有代码中缩略图行后重复写了两次|-分隔符,会渲染出多余空行,修改后的完整可用代码如下:
{|class="wikitable" style="float:right; margin-left: 10px; border: #94bf88 thin solid;" |+ ! colspan="2" style="background-color: #d9ffda; font-weight: bold; font-size: 20px; color: black; border: none;" |Artikelinformationen |- | colspan="2" style="border: none" |{{{artikelthumbnail|}}} |- | colspan="2" style= "text-align: center; border: none; font-size: 15px;"|'''Basisdaten''' |- {{#if: {{{artikeltitel|}}} | |style="border: none"|'''Artikeltitel:''' | style="width:200px; border: none;" |{{{artikeltitel}}} |- }} {{#if: {{{veröffentlichungsdatum|}}} | |style="border: none"|'''Veröffentlichung:''' | style="width:200px; border: none;" |{{{veröffentlichungsdatum}}} |- }} {{#if: {{{herausgeber|}}} | |style="border: none"|'''Herausgeber:''' | style="width:200px; border: none;" |{{{herausgeber}}} |- }} {{#if: {{{herausgeberart|}}} | |style="border: none"|'''Art:''' | style="width:200px; border: none;" |{{{herausgeberart}}} |- }} {{#if: {{{mediengruppe|}}} | |style="border: none"|'''Mediengruppe:''' | style="width:200px; border: none;" |{{{mediengruppe}}} |- }} {{#if: {{{autoren|}}} | |style="border: none"|'''Autoren:''' | style="width:200px; border: none;" |{{{autoren}}} |- }} | colspan="2" style= " text-align: center; border: none; font-size: 15px;"|'''Details''' |- {{#if: {{{absätze|}}} | |style="border: none"|'''Absätze:''' | style="width:200px; border: none;" |{{{absätze}}} |- }} {{#if: {{{sätze|}}} | |style="border: none"|'''Sätze:''' | style="width:200px; border: none;" |{{{sätze}}} |- }} {{#if: {{{wörter|}}} | |style="border: none"|'''Wörter:''' | style="width:200px; border: none;" |{{{wörter}}} |- }} {{#if: {{{zeichen|}}} | |style="border: none"|'''Zeichen:''' | style="width:200px; border: none;" |{{{zeichen}}} |- }} | colspan="2" style= " text-align: center; border: none; font-size: 15px;"|'''Links''' |- {{#if: {{{link_heruasgeber|}}} | |style="border: none"|'''Herausgeber:''' | style="width:200px; border: none;" |{{{link_heruasgeber}}} |- }} {{#if: {{{link_pdf|}}} | |style="border: none"|'''Artikel in PDF:''' | style="width:200px; border: none;" |{{{link_pdf}}} |- }} {{#if: {{{link_archiv|}}} | |style="border: none"|'''Artikel im Archiv:''' | style="width:200px; border: none;" |{{{link_archiv}}} |- }} |}
补充说明
- 如果需要实现「分区下所有字段都为空时,自动隐藏分区标题(比如Basisdaten/Details/Links)」,只需要在现有判断基础上增加一层嵌套判断即可,按需调整。
- 原有代码中出版商链接的参数名写为
link_heruasgeber,存在拼写错误(正确拼写应为link_herausgeber),如果后续调用模板时参数不生效可以检查修正。
内容的提问来源于stack exchange,提问作者UvS
相关产品推荐
相关产品推荐

