Creating Templates for SPARQL Queries

The template parameter

SPARQL already gives you the possibility to get exactly the data you want. With the integration of a template engine you can get the data you want in the way you want, i.e. you can tell the server to return the results in any custom format that fits your needs and makes it more easy for you to integrate the results in your application (e.g. HTML snippet, a custom XML schema, etc.).

If you pass a Velocity template to the endpoint, the endpoint will try to format the query results using this template with its internal Velocity engine.

To use the SPARQL endpoint with a local template file e.g. local.vm you call:

  • http://<server-URL>/PoolParty/sparql/<projectId>?query=<query>&template=local.vm&content-type=<content type produced by template>

So the following rules apply:

  • The template file has to be located in the data/resourceRoot directory of the PoolParty installation.
    The second possibility is to pass a URL (e.g. to a remote Velocity template (which doesn't have to be on the same server). The service will fetch the template before using it for formatting the results.
  • The content type produced by the template has to be specified.

Formatting the result

From within your template code you can access the following variables:

  • $result - result rows
  • $bindings - binding names (variable names used in your query)

You can access the binding sets (similar to SQL result rows) from within the velocity template using the $result variable:
The actual binding values of a binding set can be accessed through the methods of java.util.Map and will return at least a RDF Value  or more specific interfaces (see below).

The values are retrieved using the Map.get() method with the key you used in your SPARQL query as variable name.

E.g. if your SPARQL query starts like this:

SELECT ?myLabel WHERE { ... 

you can access the ?myLabel variable in the template by calling get("myLabel"):

#foreach($bindingset in $result)

If your variable is a RDF literal, you can access its data through the Literal interface:

  • Getting only the label as string:
  • Getting the language of the literal:

If your variable is a RDF resource (a URI), you can access its data through the URI interface:

  • Getting only the namespace:
  • Getting the local part of the URI:
  • Printing the entire URI as string:

If your variable is a blank node, your can access its data through the BNode interface:

  • Getting the blank node id:

You can test if the binding value is set with the following Velocity snippet:

#if ($bindingset.get("myLabel"))
// print value