Simple loop in velocity

matthew.wren's Avatar

matthew.wren

28 Aug, 2014 07:49 PM

Hi,

I'm just trying to loop through content and display it but it currently only displays the first input data's values

XML

<system-data-structure>
    <title>Documents</title>
    <document-links>
        <link-title>"Pedro Arrupe, S.J. "Men for Others""</link-title>
        <external-link>http://onlineministries.creighton.edu/CollaborativeMinistry/men-for-others.html</external-link>
    </document-links>
    <document-links>
        <link-title>"Peter-Hans Kolvenbach, S.J. "Who Our Students Become"</link-title>
        <external-link>http://onlineministries.creighton.edu/CollaborativeMinistry/Kolvenbach/Kolvenbach-SantaClara.pdf</external-link>
    </document-links>
    <document-links>
        <link-title>"Adolfo Nicolas, S.J. "Jesuit Higher Education Today"</link-title>
        <external-link>http://www.sjweb.info/documents/ansj/100423_Mexico%20City_Higher%20Education%20Today_ENG.pdf</external-link>
    </document-links>
</system-data-structure>

Velocity

#set($title = $_XPathTool.selectSingleNode($contentRoot,"//title").value)
#set($linkTitle = $_XPathTool.selectSingleNode($contentRoot,"//link-title").value)
#set($link = $_XPathTool.selectSingleNode($contentRoot,"//external-link").value)


<div class="body"> <h1>$title</h1> <div> <a href="$link"><h2>$linkTitle</h2></a> </div> </div>
  1. 1 Posted by Ryan Griffith on 29 Aug, 2014 12:37 AM

    Ryan Griffith's Avatar

    Hi Matthew,

    Looking over your Velocity, I am not seeing a loop for your <document-links> elements. Think of Velocity as a language like Java, PHP, or JavaScript where you obtain an array and loop over each element.

    When you have a moment, try the following and let me know how it works out:

    #set ( $title = $_XPathTool.selectSingleNode($contentRoot, "/system-data-structure/title") )
    #set ( $docLinks = $_XPathTool.selectNodes($contentRoot, "//document-links") )
    <div class="body">
        <h1>${_EscapeTool.xml($title.value)}</h1>
        #if ($docLinks.size() > 0)
            #foreach ($dl in $docLinks)
                #set ( $linkTitle = $_EscapeTool.xml($dl.getChild("link-title").value) )
                #set ( $link = $_EscapeTool.xml($dl.getChild("external-link").value) )
                <div>
                    <a href="${link}"><h2>${linkTitle}</h2></a>
                </div>   
            #end
        #end
    </div>
    

    Please let me know if you have any questions.

    Thanks!

  2. Ryan Griffith closed this discussion on 12 Sep, 2014 07:55 PM.

Comments are currently closed for this discussion. You can start a new one.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac