Search code examples
macosapplescriptjavascript-automation

JXA/Applescript + Pages: Create Document from template


I'm trying to create a Pages file from a Template in JXA.

I've successfully got this working in Applescript but am unable to understand the conversion to JXA.

tell application "Pages"
    activate

    set thisDocument to ¬
        make new document with properties {document template:template "my-template-name"}
end tell

From understanding the function dictionary it really should be something like:

Pages   =  Application("Pages")
Pages.activate()
t       =  Pages.Template("my-template-name") 
// produces: Error on line 2: Error: First parameter passed to Template constructor must be an object

doc = Pages.Document({
    documentTemplate: t
})

doc.make()

But it produces the said error. Other things i tried are:

t       =  Pages.Template({ 
    name:   "my-template-name",
    id:     "my-template-name"
})
// Produces no error but doesn't open any template

t       =  Pages.Template({}, "my-template-name")
// Same, no error but no template

Really looking forward to some help here.


Solution

  • I just now found out myself. To access available templates, use Pages.templates["my-template-name"].

    Resulting in the correct code:

    Pages   =  Application("Pages")
    t       =  Pages.templates["my-template-name"]
    doc = Pages.Document({
        documentTemplate: t
    })
    doc.make()