Rendering velocity templates in actions

Hello everyone!

I’m very new in confluence development, so i need some help.

I have a User object with some fields. I put it to the velocity context

My action execute method

public String execute() throws Exception {

        UserService userService = new UserService();
        User user = userService.getUser();

        Map context = MacroUtils.defaultVelocityContext();

        context.put("customer", user);

        VelocityUtils.getRenderedTemplate("/orgcharts/page.vm", context);

        return "success";
    }

Declaration of the action in atlassian-plugin.xml

<xwork name="orgchartaction" key="orgchartaction">
        <package name="orgcharts" extends="default" namespace="/users">
            <default-interceptor-ref name="defaultStack"/>
            <action name="viewuserprofile" class="com.atlassian.confluence.ldap.action.ViewOrgChartUserProfileAction">
                <result name="success" type="velocity">/orgcharts/page.vm</result>
            </action>
        </package>
    </xwork>

Questios:

  1. How correctly render template?
  2. How to show user object fields on the velocity page?

Dear Andrey,

I have no idea whether I did it the right way but it worked. Rendering the template in your execute method does not have any effect. You don’t take the result and even if you would you can’t use it.

You may try to return success only and implement a function in your action class which can be called from the Velocity template delivering the data you need.

An example of one of my action classes is: https://bitbucket.org/apurde/tree-view/src/f416ed34b8de3055f69646a3215290d8d91fecca/src/main/java/de/edrup/confluence/plugins/ManageTreeViews.java?at=master&fileviewer=file-view-default

I hope that helps.

Andreas

@andrey.bobrov The best thing to do would be to buy a $10/10 user Confluence Server license and download the source code. This is the best tutorial you can buy.

For xwork actions, all variables in the vm template should be member variables.

Here’s something that should give you an idea…

package com.example.confluence.action;

import com.atlassian.confluence.core.ConfluenceActionSupport;
import com.atlassian.user.User;

public class YourConfluenceAction extends ConfluenceActionSupport {
	
	private User user;
	
	public String doDefault() {
		UserService userService = new UserService();
		user = userService.getUser();
		return SUCCESS;
	}

	public User getUser() {
		return user;
	}
}

In /orgcharts/page.vm:

<p>hello <strong>$user.getDisplayName()</strong></p>

This should get you going.

1 Like