.contains question... is this possible?

John's Avatar

John

Aug 19, 2015 @ 09:28 PM

So I'm trying to see if a variable contains more than one string. Here's what I have right now...

#if ($keywords.contains("Alpha")
   This text displays.
#end

Thing is, I have multiple keywords per page. I'd like to see if "keywords" contains multiple words, and if so return the results that have either keyword.

This doesn't work, but am I close to something possible?

#if ($keywords.contains("Alpha" or "Bravo" or "Charlie")
   This text displays.
#end

Any ideas?

  1. 1 Posted by Ryan Griffith on Aug 20, 2015 @ 11:34 AM

    Ryan Griffith's Avatar

    Hi John,

    There are a few ways you could go about this, but the best option will depend on how things are set up.

    When you have a moment, can you describe what your $keywords variable looks like and how you are planning to defining those multiple words? For instance, is $keywords a comma separated list coming from a metadata field? Are the multiple words coming from a select box set to multiple, or multiple checkboxes?

    Thanks!

  2. 2 Posted by Wing Ming Chan on Aug 20, 2015 @ 12:05 PM

    Wing Ming Chan's Avatar

    Hi John,

    What String.contains cares about is any substring. So the substring can be anything, not just words. To create a disjunction, you can use or between boolean expressions. For example:

    #set( $keywords = "Apple, Banana, Cherry" )
    #if( $keywords.contains( "Apple, Ba" ) or $keywords.contains( "ry" ) )
        Keyword found.
    #end
    
    Wing
  3. 3 Posted by Ryan Griffith on Aug 20, 2015 @ 01:37 PM

    Ryan Griffith's Avatar

    Thank you for following up, Wing.

    What I was getting at is if the words to check is an array, he may be better off building a RegEx expression:

    #set( $keywords = "Apple, Banana, Cherry, Orange" )
    #set( $toCheck = ["Apple", "Banana"] )
    
    #set ( $joinedList = "" )
    #foreach ( $val in $toCheck )
        #set ( $joinedList = "${joinedList}${val}" )
        #if ($foreach.hasNext)
            #set($joinedList = "${joinedList}|")
        #end
    #end
    #set ( $regex = ".*(${joinedList}).*" )
    
    #if ($keywords.matches($regex))
        Keyword found.
    #end
    
  4. Ryan Griffith closed this discussion on Aug 27, 2015 @ 08:21 PM.

Discussions are closed to public comments.
If you need help with Cascade CMS please start a new discussion.

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