Search code examples
loopsif-statementparameter-passingtapestryargument-passing

How to pass a current loop value to class method in Tapestry?


I want to dynamically show available menus of links to pages depending on which type of user is logged in using Tapestry.

Part of my code in Layout.tml looks like this:

    <div class="header">
        <t:if t:test="userLoggedIn">
        <div class="menu">
            <ul>
                <t:loop t:type="loop" source="pageNames" value="pageName" class="prop:classForPageName">
                    <t:if t:test="isUserAllowedOnPage('pageName')">
                        <li>
                            <t:pagelink page="prop:pageName.name">${pageName.displayName}</t:pagelink>
                        </li>
                    </t:if>
                </t:loop>
            </ul>
        </div>
        </t:if>
        <div style="clear:both;"></div>
    </div>

In my Layout.java I have a following method:

public boolean isUserAllowedOnPage(String pageName) {
    // My logic here, returns either true or false
}

The problem is, I do not know how to pass the actual page name parameter to isUserAllowedOnPage(String pageName) method, because with the following line of tml code
"isUserAllowedOnPage('pageName')" I pass an actual string, "pageName" instead of one of the desired values (for example, "Index", "About", "Contacts"...).


Solution

  • Your loop specifies value="pageName" which means that tapestry will update the pageName property in your page each time it iterates through the loop. So, you don't need to pass it to a method since it's already set each time you invoke the method. You could just do the following:

    TML

    <t:loop source="pageNames" value="pageName">
        <t:if t:test="userAllowedOnPage">
            ...
        </t:if>
    </t:loop>
    

    Java

    @Property
    private List<String> pageNames;
    
    @Property
    private String pageName;
    ...
    public boolean isUserAllowedOnPage() {
        // some calculation based on pageName
    }