Velocity Access Array value by key?

Is there a way to access velocity array element by a key? For example, I want to access the first element of the array in this code:

#set($blogPosts = $core_v2_blogPost.List("%{ BlogId = 4, IncludeSubGroups = 1, IncludeUnpublished = 0, PageIndex = 0, PageSize = 7, SortOrder = 'Ascending }"))
		    #set($blogPosts = $core_v2_utility.AsArray($blogPosts))
		    <script>console.log($core_v2_utility.ToJson($blogPosts[0]);</script>

Parents
  • Server-side JavaScript/JSM tends to be better suited for even simple data manipulation. That said, for rendering out HTML as in a widget, Velocity still wins out.

    There's no supported direct way of accessing array elements in Velocity. Common solutions tend to use a loop and capture the first item. Some scripts use a trick with $blogPosts.get_Item(0). While this will likely work for you, I usually recommend against it since it only works due to how .NET reflection interacts with the Velocity runtime.

    Also, .AsArray() will not do anything useful within Velocity scripts. It's a legacy method for JSM to help IList objects act more like arrays. 

Reply
  • Server-side JavaScript/JSM tends to be better suited for even simple data manipulation. That said, for rendering out HTML as in a widget, Velocity still wins out.

    There's no supported direct way of accessing array elements in Velocity. Common solutions tend to use a loop and capture the first item. Some scripts use a trick with $blogPosts.get_Item(0). While this will likely work for you, I usually recommend against it since it only works due to how .NET reflection interacts with the Velocity runtime.

    Also, .AsArray() will not do anything useful within Velocity scripts. It's a legacy method for JSM to help IList objects act more like arrays. 

Children