9. Accessing Magnolia Context

In Magnolia, accessing the context within Groovy scripts is a powerful capability that allows developers to interact with content, components, and request parameters effectively. In this tutorial, we will explore how to access the Magnolia context using Groovy scripts, covering essential use cases and providing examples to demonstrate each scenario.

Basic import and Initialisation

To access context functions, you must import and initialise the following:

import info.magnolia.context.MgnlContext
def ctx = MgnlContext.getInstance()

Accessing Node Data

def nodeData = ctx.getJCRSession("website").getNode("/path/to/node")
println("Node Title: ${nodeData.getProperty("jcr:title").getString()}")

In this example, we access a node in the Magnolia repository and retrieve its "jcr:title" property. Replace "/path/to/node" with the actual path to the node you want to access.

[Tip: You can use getProperty("propertyName").getString() to access different properties of the node.]

Accessing Component Data

def componentData = ctx.getArea("main").getComponent("myComponent")
println("Component Title: ${componentData.get("title")}")

Here, we access a component in the "main" area and retrieve its "title" property.

[Tip: Use getArea("areaName") to access different areas of your page.]

Looping through Child Nodes

This code fetches the child nodes of a parent node and iterates through them:

def parentNode = ctx.getJCRSession("website").getNode("/path/to/parent")
def childNodes = parentNode.getNodes()
childNodes.each { childNode ->
    println("Child Node Name: ${childNode.getName()}")
}

[Tip: You can use getChild("childNodeName") to access a specific child node by name.]

Accessing a DAM asset by its UUID

In this example, we access a DAM asset using its UUID:

import info.magnolia.context.MgnlContext
import info.magnolia.dam.api.Asset
import info.magnolia.dam.api.AssetProviderRegistry
import info.magnolia.objectfactory.Components
import info.magnolia.dam.api.ItemKey

def itemKey = new ItemKey("jcr", "12345678-90ab-cdef-ghij-klmnopqrstuv")
try{
    // Access the AssetProviderRegistry
    def assetProviderRegistry = Components.getComponent(AssetProviderRegistry.class)
    
    // Obtain the default DAM provider using the correct method name
    def assetProvider = assetProviderRegistry.getProviderById("jcr")
    
    // Retrieve the asset by UUID
    def asset = assetProvider.getAsset(itemKey)
    
    if (asset != null) {
        println("Asset Title: ${asset.getName()}")
        println("Asset MIME Type: ${asset.getMimeType()}")
        // Perform further operations with the asset here
    } 
}catch(e){
     println("Asset not found with UUID: ${itemKey.asString()}")
}

You can replace "12345678-90ab-cdef-ghij-klmnopqrstuv" with the actual UUID of the asset you want to access. This code retrieves the asset's title, MIME type, and allows you to perform additional operations with the asset.

[Tip: You can also access DAM assets by path, metadata, or other criteria using the DAM service provided by Magnolia's context.]

Accessing Categories

How to access categories in Magnolia

import info.magnolia.context.MgnlContext

// Define the path to your categories
def categoriesPath = "/your/category/path"

// Obtain the JCR session for the category workspace
def session = MgnlContext.getJCRSession("category") 

// Check if the categories path exists
if (session.nodeExists(categoriesPath)) {
    // Get the categories node
    def categoriesNode = session.getNode(categoriesPath)

    // Iterate over each category node
    def categoriesIterator = categoriesNode.getNodes()
    while (categoriesIterator.hasNext()) {
        def categoryNode = categoriesIterator.nextNode()
        def uuid = categoryNode.getProperty("jcr:uuid").getString()
        println("Category: ${categoryNode.getName()} (${uuid})")
    }
} else {
    println("Categories path does not exist.")
}

[Hint: categoriesPath "/" will return all categories from root]