Search code examples
gradlegroovyincludetemplate-engine

How/Can I include secondary files into a file during gradle's expand/copy?


I am trying to template various XML files. What I want to do is be able to build out a Parent XML by including several Child XML files. This should happen during the expand()->copy() using the SimpleTemplateEngine

as an example:

Gradle:

processResources {
     exclude '**/somedir/*'
     propList.DESCRIPTION = 'a description goes here'
     expand(propList)
}

Parent.XML:

<xml>
   <line1>something</line1>
   <%include file="Child.XML" %>
 </xml>

The documentation states that the SimpleTemplateEngine uses JSP <% syntax and <%= expressions, but does not necessarily provide a list of supported functions.

include fails with it not being a valid method on the resulting SimpleTemplateScript, maybe I meant eval?

The closest I've come to getting something to work is:

<xml>
   <line1>something</line1>
   <% evaluate(new File("Child.xml")) %>
 </xml>

That results in 404 of the Child.xml as it's looking at the process working directory, rather than that of the Parent file. If I reference it as "build/resources/main/templates..../Child.xml", then I get 'unexpected token: < @ line....' errors from parsing the Child.

Can this be done? Do I need to change template engines, if that's even possible? Ideally it should process any tokens in Child as well.

This is all very simple in JSP. I somehow got the impression I can treat these files like they're GSP, but I'm not sure how to properly use the GSP tags, if that's even true.

Any help, as always, is greatly appreciated.

Thank you.


Solution

  • This documentation doesn't mention JSP. The syntax for the SimpleTemplateEngine is ${}.

    Using Gradle 3.4-rc2, if I have this build.gradle file:

    task go(type: ProcessResources) {
        from('in') {
            include 'root.xml'
        }
    
        into 'out'
    
        def props = [:]
        props."DESCRIPTION" = "description"
        expand(props)
    }
    

    where in/root.xml is:

    <doc>
        <name>root</name>
        <desc>${DESCRIPTION}</desc>
    
    ${new File("in/childA.xml").getText()}
    </doc>
    

    and in/childA.xml is:

    <child>
        <name>A</name>
    </child>
    

    then the output is:

    <doc>
        <name>root</name>
        <desc>description</desc>
    
    <child>
        <name>A</name>
    </child>
    
    </doc>