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

Hash expansion to macro arguments (Python **kwargs style)

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 2.3.28
    • 2.3.30
    • engine
    • None

    Description

      Hello,

      We heavily rely on Freemarker macros to build a helper template API, but have had to make large workarounds for passing contents of hashes as macro arguments, for several years. (In truth I should have made this ticket much sooner!)

      It would help greatly simplify our work to have hash expansion to macro arguments, like this:

      <#macro myMacro arg1 arg2 arg3="value3">...</#macro>
      
      <#assign myHash = {"arg1":"value1", "arg2":"value2"}>
      
      <@myMacro **myHash/><#-- the hash contents are passed as parameters, instead of the hash itself -->
      

      This exists in Python:

      def test_var_args_call(arg1, arg2, arg3):
          pass
      
      kwargs = {"arg3": 3, "arg2": "two"}
      test_var_args_call(1, **kwargs)
      

      Essentially the hash contents fill in any arguments not explicitly specified.

      For the case where arguments are specified in addition to the hash, you may need to decide on a good syntax, e.g.:

      <@myMacro arg1="value1" **myHash/>

      This example doesn't have much precedent in freemarker syntax but is fairly understandable.

      Although we don't need it nearly as much, the same could be done with lists and function arguments:

      <#function myFunc arg1 arg2>...</#function>
      
      <#assign myList = ["val1", "val2"]>
      ${myFunc(*myList)}
      <#assign myList = ["val2"]>
      ${myFunc("val1", *myList)}
      

      Again similar to Python:

      def test_var_args_call(arg1, arg2, arg3):
          pass
      
      args = ("two", 3)
      test_var_args_call(1, *args)
      

      You might want this for consistency, although in practice the hash expansion will be many times more useful to us.

      If there's a lack a manpower I could try to see what I can do digging into the source, but wanted to bring this up for discussion first. It doesn't appear hard to implement to dump a hash into the macro args map, but there is defining the syntax.

      We use Freemarker 2.3.28 at the moment.

      Thank you

      Attachments

        Activity

          People

            Unassigned Unassigned
            pplx Pascal Proulx
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: