Uploaded image for project: 'Apache Freemarker'
  1. Apache Freemarker
  2. FREEMARKER-75

New built-in ?as("variableName") to store the left-hand operand to a variable.

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Major
    • Resolution: Duplicate
    • 2.3.26-incubating
    • None
    • engine
    • None

    Description

      When coding templates, one often runs into a situation like this:

      <#if (foo.bar.baz.expensiveCall())!false >
           ${ foo.bar.baz.expensiveCall() }
      </#if>
      

      Solving it with currently available things is something like

      <#assign cached = (foo.bar.baz.expensiveCall())! >
      <#if cached?has_content() >
           Hello, ${ cached }
      </#if>
      

      In short, passing around the information that a value could not be obtained is a bit cumbersome.

      What I suggest is a built-in that would capture a value of an expression on the left to a new variable and pass it along.

      <#if (foo.bar.baz.expensiveCall())!?as("cached")?has_content >
           Hello, ${ cached }
      </#if>
      

      The benefits is that there is need to compute the expression twice or do the assignment.

      Speaking of simplifying, the expression above could also be simplified by another built-in, a "reversed" then(). (For that I will file another jira.)

      ${ "Hi, "?if( expensive()?as("cached"), "") + cached }     // For conditional prefixes
      
      ${ expensive()?as("cached")!false + ", good bye!"?if(cached) }     // For conditional suffixes
      
      ${ "Hi, ${expensive()?as("cached")!false}, again!"?if(cached) }     // For conditional surrounding
      

      The new ?as() built-in could be also used for a more convenient way of assigning wile printing:

      ${"Hi ${user}"?as("greet")}.
      ${ greet }, again.
      

      I hope my explanation does make sense.
      Thanks for considering.

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              pekarna Ondra Žižka
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: