Introduction
This article will show you a template copier application in Google Apps Script.
This application will automatically copy a template to your MyDrive when you access the deployed URL.
This is useful for anyone who wants to save time and effort when developing web applications with HTMLService.
Application
This code is for an application that is deployed to copy templates.
When you access the deployed URL, the "OPEN FILE" link will be displayed on the screen.
The application Code1.gs is deployed as a web application.
When you access the URL, the Template file, which includes Code2.gs, index.html, css.html and javascript.html are copied.
A link to the file is displayed in the browser.
Clicking the link opens the file that copied the Template.
Source Code
Code1.gs
const FILE_ID = "FILE_ID";
function doGet() {
const copyFileUrl = copyFileToMydrive();
const html = '<a target="_blank" href="' + copyFileUrl + '">OPEN FILE</a>';
return HtmlService.createHtmlOutput(html);
}
function copyFileToMydrive() {
const file = DriveApp.getFileById(FILE_ID);
const name = "Copy of " + file.getName();
const copyFile = file.makeCopy(name);
return copyFile.getUrl();
}
As a template to copy from, we will prepare the following code.
The contents of the code are up to you.
The following is just one example, so please feel free to write it as you like.
Template:
Code2.gs
function doGet() {
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setTitle("Title");
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function returnHello(name) {
return "Hello" + " " + name;
}
index.html
<!DOCTYPE html>
<html>
<head>
<?!= include("css"); ?>
</head>
<body>
<input type="text" id="name">
<button id="bt">submit</button>
<?!= include("javascript"); ?>
</body>
</html>
css.html
<style>
#name {
width: 10vw;
height: 5vh;
font-size: 20px;
}
</style>
javascript.html
<script>
document.getElementById("bt").onclick = runHello;
function runHello() {
var name = document.getElementById("name").value;
google.script.run
.withFailureHandler(onFailure)
.withSuccessHandler(onSuccess)
.withUserObject("how are you?")
.returnHello(name);
}
function onSuccess(result, userObject) {
alert(result + " " + userObject);
}
function onFailure(e) {
alert([e.message, e.stack]);
}
</script>
This template app is as follows:
By changing the FILE_ID in Code1.gs, you can copy any file in Google Drive, such as scripts, spreadsheets, or documents.
Class File > makeCopy() Method