Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check existence of tiles attribute before inserting it into the page

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?

like image 436
Bilal Mirza Avatar asked Oct 07 '22 00:10

Bilal Mirza


2 Answers

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.

like image 69
Bilal Mirza Avatar answered Oct 10 '22 01:10

Bilal Mirza


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>
like image 27
Ian Avatar answered Oct 10 '22 03:10

Ian