I am using tiles in struts2 application. While defining base layout I have defined an attribute "scriptFile".
<definition name="baseLayout" template="/application/base-layout.jsp" >
...
</definition>
<definition name="custom.tiles" extends="baseLayout">
<put-attribute name="scriptFile" value="js/custom-script.js"></put-attribute>
</definition>
If developer provides "scriptFile" in tiles definition file, "tiles.xml", this script file should be included using following line
<script language="javascript" src="<tiles:insertAttribute name="scriptFile"></tiles:insertAttribute>"></script>
But if scriptFile attribute is not defined, this line must be skipped.
How can I check the existence of "scriptFile" attribute in tiles. Is there any better way to do this thing?
I tried
<t:useAttribute name="scriptFile" id="script" classname="java.util.List" ignore="true"/>
<%
if(script != null) {
... include script
}
%>
JSTL can also be used here.
I was able to solve a similar problem by using the defaultValue attribute. This way, you won't get an exception if the attribute doesn't exist. In this case, if the page doesn't need to include extra JavaScript then the tiles template will just add an empty string
JSP
<tiles:insertDefinition name="portalTemplate">
<tiles:putAttribute name="body">
<h1>Body</h1>
</tiles:putAttribute>
<tiles:putAttribute name="js">
<script src="script.js"></script>
</tiles:putAttribute>
</tiles:insertDefinition>
Tiles Template JSP
<html>
<body>
<tiles:insertAttribute name="body"/>
<script src="/public/libs/jquery/jquery-2.1.1.min.js"></script>
<!-- Include extra JS after JQuery -->
<tiles:insertAttribute name="js" defaultValue=""/>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With