You can create new pages with JavaScript Button for Confluence. This allows for templating. You can add a button to a page, and when invoked, a new page will be created. You can use JavaScript to customize the page content if you want and you can use fields to allow your users to customize how to create the page.
The following example shows how to use a field to fetch the page title, and a field to fetch the type of the page:
To create the page itself, use the following JavaScript Code:
function create(title, type, page) {
if (type === "Instruction") {
//do something special here
}
return {
parentId: page.id,
spaceId: page.spaceId,
title: title,
body: {
representation: "atlas_doc_format",
value: JSON.stringify({
type: "doc",
content: [{
type: "paragraph",
content:[{
text: "Type: " + type,
type: "text"
}]
}],
version: 1
})
}
};
}
The following function allows you to create a template for any existing confluence page: Create a new empty confluence page and add a JavaScript Button a the very top of the page. Then configure the Button as follows (where you replace PAGE_ID with the id of the page you want to create a template for, you can find this id in the URL of the page):
- Button Caption: Create Template Function
- Function Name: createTemplateFunction
- Function Parameter: $page, PAGE_ID
- Result Location: $page
- Code:
async function createTemplateFunction(page, contentId) {
const body = JSON.parse(page.body.atlas_doc_format.value);
const res = await api
.asUser()
.requestConfluence(route`/wiki/api/v2/pages/${contentId}?body-format=atlas_doc_format&serialize-ids-as-strings=true`);
const originPage = await res.json();
const result =
`/*
The following function can instantiate a copy of Page
${originPage.title}
To use it: Create an empty page with a JavaScript Button with
the following configuration and then invoke that button.
Function Name: setup
Function Parameter: $page
Result Location: $page
JavaScript Code:
*/
function setup(page) {
const bodyValue = ${JSON.stringify(JSON.parse(originPage.body.atlas_doc_format.value), null, " ")}
return {
id: page.id,
title: page.title,
status: page.status,
spaceId: page.spaceId,
parentId: page.parentId,
version: {
number: page.version.number + 1,
message: "Instantiate Template"
},
body: {
representation: "atlas_doc_format",
value: JSON.stringify(bodyValue)
}
}
}`;
body.content.push({
type: "codeBlock",
attrs: {
language: "javascript"
},
content: [{
text: result,
type: "text"
}]
});
page.body.atlas_doc_format.value = JSON.stringify(body);
page.version.number = page.version.number + 1;
page.version.message = `Generated Setup Function for page ${originPage.title}`;
return page;
}
When invoking the button, a new Code Section appears on the page, containing the function that your user needs to execute to create a copy of the page with PAGE_ID.