Search code examples
javascriptcssvelocityconfluence

How to reference css and js in velocity template?


I am trying to access my css and js file (which are located at resources/css/stylesheet.css and ../js/..), but I am not sure how to.

I have already tried to use $webResourceManager.requireResource(xxx:xxx) between the and tags, but it just prints $webRes... on the webpage. I have also used the #requireResource(xxx:xxx) in the head. It didn't print it on the page but it didn't work either.

In the atlassian-plugin.xml

<web-resource key="statPlugin-resources" name="statPlugin Web Resources">
        <dependency>com.atlassian.auiplugin:ajs</dependency>

        <resource type="download" name="statPlugin.css" location="/css/statPlugin.css"/>
        <resource type="download" name="statPlugin.js" location="/js/statPlugin.js"/>
        <resource type="download" name="images/" location="/images"/>
        <resource type="velocity" name="test" location="/templates/test.vm"/>

        <context>statPlugin</context>
</web-resource>

in page.vm

<head>
    <title>Stat Plugin Configuration</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

</head>

$webResourceManager.requireResource("com.tdk.plugin:statPlugin-resources")

<body>
...
</body>

Error message: Uncaught ReferenceError: addCard is not defined at HTMLButtonElement.onclick (stat-config:33)

So the js file is not found.


Solution

  • The answer is simple, but it was very hard to find, because of the outdated documentation. In my first attempt, I tried to use the WebresourceManager, which no longer is deprecated. You have to use ConfluenceWebresourceManager. You can get access to it when you use a component import.

    To give your Velocity plugin the resource manager you have to use

    context.put("confluenceWebResourceManager",confluenceWebresourceManager");
    

    in the doGet or doPost of your servlet.

    In the template itself you have to wirte following:

    <head>
    ...
    </head>
        $confluenceWebResourceManager.requireResource("com.company.plugin.pluginName:pluginName-resources")
    <body>
    ...