首页 > 解决方案 > 速度解析 + 全局变量与宏

问题描述

在我的项目中,我有很多 html 代码块,我在不同的地方重复使用这些代码块,但略有不同。例如,我有一个定义信息横幅的代码块,但文本和配色方案是不同的。

我看到了两种将它“包含”到我的主模板中的方法:

1.

#set( $infoBannerText = "This is an info banner..." )
#set( $infoBannerColor = "YELLOW" ) ## predefined map with color-related properties
#parse( "info-banner" )
  1. 之前定义#macro( info_banner $infoBannerText $infoBannerColor )过:
#info_banner( "This is an info banner..." "YELLOW" )

我看到以下优点/缺点:第二个在缺少变量定义或意外覆盖变量方面更强大。而第一个具有更好的性能,并且允许我可以将可重用部分存储在单个文件中的更清晰的结构。使用宏感觉就像我最终会得到一个缺乏清晰度的大宏文件。

不知何故,我更喜欢第一个解决方案,但想知道“最佳实践”是什么或您有什么经验。

标签: velocity

解决方案


您可以混合使用两种方式:

#macro(info_banner, $infoBannerText, $infoBannerColor)
  #if(!$infoBannerText) Missing banner text! #end
  #if(!$infoBannerColor) Missing banner color! #end
  #parse('info-banner')
#end

#info_banner( "This is an info banner..." "YELLOW" )

无论哪种方式,我都没有真正看到任何性能问题。一个好的做法是将所有已解析的块收集到某个/inc/子文件夹中,这样它们就不能被直接称为顶级模板。


推荐阅读