We use cookies to make your viewing experience better. By accepting you consent, you agree to our Cookie policy

Accept
Improve your Craft CMS skills

How To Copy The Templates Directory In Craft CMS

10 min read
Shape April 2022 HR 189

Ever needed to quickly duplicate templates in Craft CMS but weren't sure how to properly copy the templates folder? This guide has you covered with proven techniques to securely copy the templates directory between environments or servers. Learn how to locate the templates folder, handle permissions, update configuration, debug issues, and reuse templates efficiently. Whether you're a developer managing staging environments or a client migrating Craft sites, copying templates saves huge amounts of time and effort. Read on to master the ins and outs of securely duplicating templates in Craft CMS.

The templates directory in Craft CMS is located under /path/to/craft/templates. You can copy it via the control panel, FTP, CLI commands, or custom scripts. After duplicating, update configuration, test across browsers, and secure permissions on the copied templates. This allows efficiently reusing and syncing templates across environments.

Copying Templates in Craft CMS

Overview of Templates in Craft CMS

Templates are a core part of the Craft CMS content management system. They control how content is displayed on the frontend of a Craft site. Templates allow you to take content from your Craft CMS backend and output it on the frontend in a structured way.

For example, you may have a blog channel in Craft CMS with hundreds of blog posts. You'll create a blog template that loops through each of those posts and displays them on the frontend in a certain layout and style. Templates give developers control over how the content is presented.

Templates are made up of HTML, CSS, Twig code, and can pull in content dynamically from the Craft CMS backend. Templates help to separate content from presentation when building a website in Craft.

Reasons for Copying Templates

There are a few common reasons you may want or need to copy an existing template in Craft CMS:

  • Using an existing template as the starting point for a new template. It's often easier to copy and modify than building a new template from scratch.

  • Creating templates for different sections or channels that should have the same or very similar markup and styling. For example, copying a blog template to use as the base for an news template.

  • Backing up templates before making edits. Copying a template allows you to easily revert back if needed.

  • Duplicating templates across different environments like dev, staging and production. Keeping templates in sync across environments.

  • Speeding up development by rapidly creating similar templates. Copying and then customising saves time vs coding from nothing.

Copying an existing template can be a huge time saver compared to rebuilding the same structure and markup from scratch. It also ensures consistency across similar templates.

Overview of Copying Process

The process for copying a template in Craft involves just a few simple steps:

  • Accessing the Craft CMS control panel and navigating to Settings > Templates. This is where all existing templates are listed.

  • Clicking on the template you want to copy. That will open up the template editor.

  • Clicking the gear icon in the top-right corner of the template editor and selecting "Duplicate".

  • optionally, renaming the duplicate template and updating any template settings.

  • Saving the duplicated template.

The duplicated template is now an exact copy of the original. You can then go in and customise the markup, styling, and logic of the duplicated template for its specific purpose without affecting the original template it was copied from.

Copying a template in Craft CMS is quite straightforward. After accessing the template you want to copy, it's just a couple clicks to duplicate it and have a new copy you can modify and work from. It saves time starting from an existing template rather than building one from scratch.

Locating the Templates Directory

Default Template File Paths

In a standard Craft CMS installation, templates are stored within the templates folder in the craft installation directory.

For example, if Craft is installed at /var/www/html/mysite, then the templates would be located at /var/www/html/mysite/templates.

Within the templates folder is where all the .html and .twig template files live that control frontend display in Craft. These template files can be organised into sub-folders within templates to keep things organised.

The default templates folder contains a few files out of the box like index.twig (the homepage template), _layout templates, and error page templates. All user-created templates will also reside here.

So in summary, the default location for templates in Craft is the templates folder within the

Craft install directory. And this can contain sub-folders and all the .html/.twig files that handle frontend presentation and content display.

Templates Folder in Different Environments

It's common to have different environments for Craft CMS - like a local development environment, a staging environment, and a live production environment.

The template file location may be different across these environments depending on the server setup and file structure.

For example, on a local dev environment, the templates may be under /Users/YourName/Sites/myproject/templates.

On the staging server, it could be /var/www/staging/myapp/templates.

And on production something like /var/www/production/myapp/templates.

So even though the templates folder will still be called templates, the full server file path to that templates folder can vary across environments.

It's important when moving templates between environments to pay attention to the folder structure and path needed for that particular server setup.

Finding the Templates Folder

If you're unsure of the exact location of the templates folder for your Craft install, there are couple easy ways to find it:

  1. Check your Craft config file - It will contain a paths.templates value which shows the file path.

  2. Go to Settings > General in the Craft CP. The "Template Path" shown here displays your templates folder location.

  3. Use FTP/SFTP to explore the folder structure on the server and locate the templates folder.

  4. Use a terminal/command line to inspect the directory structure starting from your Craft installation folder.

  5. Some IDEs like PHPStorm can directly link to the templates folder for easy access.

So if ever unsure where templates live, the config settings in Craft's control panel or inspecting the file structure on server are the best ways to definitively locate the templates directory being used.

Knowing the exact file path to the templates folder is handy when you need to access the files directly via FTP/SFTP or reference the folder location from within code or config files. Craft provides a couple convenient ways to find the templates path if you don't already know it.

Manually Copying the Templates Folder

Using File Explorer

One way to manually copy the templates folder in Craft CMS is by using your operating system's file explorer.

On Windows, you would use File Explorer. On Mac, the Finder app. And on Linux, a file manager like Nautilus or Dolphin.

The process involves:

  1. Navigating to the Craft templates folder using the file explorer.

  2. Selecting the templates folder.

  3. Right clicking on the folder and choosing "Copy".

  4. Browsing to the destination folder where you want to copy the templates folder.

  5. Right clicking within the destination folder and selecting "Paste".

The templates folder and all its contents will then be copied over to the new location.

This manual copy and paste process works well for small to medium sized template folders. For large template folders, copying via file explorer may be painfully slow or error-prone.

Using FTP

FTP can also be used to manually copy over the templates folder in Craft CMS.

Here are the steps:

  1. Connect to your server via an FTP client like FileZilla.

  2. Navigate to the folder containing the templates folder.

  3. Select the templates folder in the FTP client.

  4. Right click on templates and choose "Copy" or "Duplicate" depending on your client.

  5. Browse to the destination folder on the server where you want to copy the templates folder.

  6. Right click within the destination folder and select "Paste" or "Duplicate".

  7. Wait for the full templates folder and contents to copy over.

FTP may provide slightly faster copying compared to file explorers when dealing with large template folders or slower connections. But it still requires manually initiating and monitoring the copy process.

Handling Large Folders

When dealing with very large template folders, here are some tips:

  • Compress the templates folder into a .zip archive first. Copy over the smaller .zip file instead, then extract.

  • Use a terminal/command line instead and leverage shell utilities like cp or rsync for faster copying.

  • Do the copy process overnight or during off-peak hours if time allows.

  • Copy over one sub-folder at a time instead of the entire parent templates folder.

  • Temporarily disable any antivirus software during the copy process to speed things up.

  • Use a utility like Robocopy on Windows for multi-threaded copying and faster transfers.

  • Set the connection mode in your FTP client to "Binary" for quicker copying of a large number of small files.

Manually copying large template folders comes with some challenges. But using the right tools and techniques can help optimise the process and reduce the time needed.

Copying Templates via CLI

CLI Copy Command Syntax

The Craft CMS CLI (command line interface) provides a way to copy templates directly from the terminal.

The copy command syntax is:

./craft template/copy

sourceTemplateHandle targetTemplateHandle


For example, to copy a template called blog to a new template called news, the command would be:


./craft template/copy blog news


The source template handle goes first, then the new handle you want to copy it to.

Some other examples:

./craft template/copy products product-uk

./craft template/copy homepage home-2022


The copy command creates a duplicate of the source template with the new handle provided.


You can also pass flags like --overwrite to force overwriting the target template if it already exists:


./craft template/copy --overwrite blog news


And -f to suppress confirmation prompts:


./craft template/copy -f blog news


So the CLI provides a straight-forward way to programmatically copy a template by passing the source and target handles.

CLI Permissions and Setup

To run Craft CMS template copy commands from the CLI, you need:

  • Local terminal access to run console commands.

  • Craft CLI executable in the path. Usually ./craft from the project root.

  • A user account with permission to manage templates.


Without proper permissions, you'll get "Unable to perform action" errors when running CLI copy commands.


To setup, create a CLI user account in Craft's control panel with template creation/editing privileges.


Then reference the username/password when running CLI commands:


./craft --username=myUser --password=myPassword template/copy blog news


Or even better, create a craft.yaml file with the credentials pre-defined so you don't have to pass them manually each time.


Proper CLI permissions and setup is crucial for executing template copy operations from the command line smoothly.

Custom CLI Scripts

For frequent or scheduled template copying, you can create custom CLI scripts that automate the process.

Some examples:

Bash script to copy templates nightly from production to staging:


#!/bin/bash


./craft --username=cliUser --password=secret template/copy header-prod header-staging

./craft --username=cliUser --password=secret template/copy footer-prod footer-staging

# etc...


A Node.js script to copy templates after deploy:


const { exec } = require('child_process');


exec('./craft template/copy home-prod home-live', (err, stdout, stderr) => {

if (err) {

console.error(err);

return;

}

console.log(stdout);

});


Python script to duplicate templates with dated handles:


from subprocess import run


# Duplicate home page template with date handle

result = run(['./craft', 'template/copy', 'home', f'home-{date.today()}'])

print(result.stdout)


Automating template copies through custom scripts helps streamline managing templates across environments.

Updating Configuration

Template Path Settings

When copying templates between environments or servers, some configuration updates may be required for the new templates to work properly.

The main setting to check is the templatePath config value, found in config/general.php.

This defines the server file path to the templates folder for Craft:

return [

'templatePath' => '/path/to/mysite/templates',

];

If copying templates to a new environment, update templatePath to match the new server folder path.


For example, changing from:

'templatePath' => '/Users/myuser/Sites/dev/templates'


To:

'templatePath' => '/var/www/html/production/myapp/templates'

This ensures Craft loads the templates from the proper location.

The template path is also shown under Settings > General in the control panel.

Config Differences Across Environments

Other configuration that may need updating depends on differences between source and target environments.

For example, the database connection details in .env often varies across dev, staging, production. Update .env with the new database credentials when copying templates.

Same with any other environment-specific config values like cache settings, servers, environment variables, and more as needed.

When templates are copied from one environment to another, review all configuration and make tweaks for the new target environment.

Cache and Config Clearing

After copying templates, clear caches and rebuild config to avoid issues:

  • Clear Craft caches via Utilities > Clear Caches

  • Clear server caches like Redis, Memcached, OPcache if used

  • Rebuild Craft config with ./craft cms/config/rebuild

  • Refresh frontend caches and CDN as needed

This clears out any stale data or config that could conflict with the new copied templates.

Avoid errors like missing templates or incorrect template caching by flushing caches and rebuilding configuration.

Test the site thoroughly after copying templates. Watch for console warnings or errors indicating configuration issues.

Updating configuration settings for the new environment, clearing caches, and testing thoroughly helps ensure a smooth template copying process with no surprises down the road.

Testing Copied Templates

Frontend vs Backend Testing

When copying templates from one Craft CMS environment to another, be sure to thoroughly test both the frontend and backend after copying.

On the frontend, verify:

  • Templates are loading correctly with expected content

  • CSS and JavaScript files are loading properly

  • Images, fonts, and assets are displaying as expected

  • Site pages are reachable with proper status codes

Basically validate the full front-facing site is working.

For the backend:

  • Check templates are visible in the CMS control panel

  • Open each template and validate fields and settings

  • Confirm templates are linked to the correct entries/channels

  • Test editing content in the control panel that uses the templates

Testing both frontend and backend helps catch any issues that may arise from differences in environments, configuration values, or server setups.

Cross-Browser Testing

In addition to environment testing, validating copied templates across major browsers is important:

  • Chrome

  • Firefox

  • Safari

  • Edge

  • Mobile browsers like Chrome for Android and Safari for iOS

This helps uncover any cross-browser compatibly issues that may exist in the copied templates when it comes to CSS, JavaScript, markup, or behavior.

Some problems to watch for:

  • Visual styling inconsistencies

  • JavaScript errors

  • HTML/CSS errors

  • Media queries not working as expected

Fixing cross-browser issues in the copied templates helps ensure a consistent experience for all your site visitors regardless of their browser.

Handling Template Issues

If issues arise after copying templates, here are some troubleshooting tips:

  • Check for JavaScript console errors for clues. Fix JS bugs.

  • Enable Craft debugging temporarily to uncover critical errors.

  • Use browser dev tools to audit files loaded, network requests, element selector.

  • Review Craft logs for any errors getting triggered.

  • Try swapping back the original template as control test.

  • Delete any problematic caches and try re-copying templates.

  • Double check environment config values like template paths.

  • Compare working and broken environments for differences.

  • Verify file permissions allow Craft/server to access templates.

For major issues, consider doing a fresh re-copy, audit all environment settings, and test again systematically.

Patience and slowly eliminating variables is key. Save backups of templates in case needed to revert.

Thorough frontend testing, cross-browser validation, and systematic debugging helps smooth over any template issues after copying.

Security Considerations

Template Permissions

When copying templates between environments, proper permissions should be set on the copied templates to prevent unauthorised access.

Some best practices:

  • Set the owner and group to the web server user like www-data or apache.

  • Make templates read-only for the web server owner.

  • Restrict permissions for other users - no read/write/execute.

  • Double check permissions didn't loosen during the copy process.

  • Consider using access control lists (ACL) for finer grained control.

Securing permissions ensures the web server can read templates to deliver pages, while other users are restricted from modifying them.

Permissions can be set via the command line with chmod, via FTP clients, or file explorers.

Locked down permissions help prevent unapproved changes if a server is compromised.

Encryption and Protection

For highly sensitive template files, additional encryption and protection methods can be used:

  • Server-side encryption file systems like eCryptfs.

  • Encrypted digital containers like VeraCrypt.

  • Encrypting just certain secure files with GPG/PGP encryption.

  • Replacing passwords/API keys with environment variables.

  • Obfuscating/minifying JavaScript files with limited access.

However, each of these adds complexity. Balance security versus convenience.

If templates contain truly confidential data, then encryption provides an added layer of protection.

Access Control Strategies

To securely manage access to copied templates, some strategies include:

  • Principle of least privilege - only grant essential permissions.

  • Mandatory access control with strict policies set globally.

  • Role-based access control defining permissions based on user roles.

  • Attribute-based access control using user attributes to set access.

  • Rule-based access control with if-then conditional policies.

  • Time-based restrictions on when users can access templates.

  • IP address restrictions allowing only certain IP ranges.

Combining these models using either Craft CMS tools or server-level controls allows

fine-grained management over template access.

Proper access strategies prevent unapproved changes and mitigate risks of copied templates getting exploited.

Thoroughly reviewing permissions, encryption options, and access control policies helps balance usability for developers while still maintaining security on copied templates.

Template Debugging Tips

Identifying Error Sources

Debugging issues with copied templates involves pinpointing the root cause:

  • Review frontend for JavaScript errors using dev tools console. Fix JS bugs.

  • Check Craft logs at storage/logs for critical PHP issues.

  • Enable Craft debugging mode to show full error details.

  • Confirm database is accessible - related errors point to connectivity issues.

  • Test unmodified default templates to isolate custom code problems.

  • Disable plugins one-by-one to see if problem persists. Helps find conflicting plugins.

  • Clear all caches in case of stale config or cached code.

  • Validate folder permissions allow system to read templates.

Methodically eliminating variables helps narrow down what is causing the copied template to break.

Useful Tools and Logs

Some helpful tools for debugging Craft templates:

  • Craft Stack Trace - plugin for inspecting stack traces of errors.

  • Template Helper - provides debugging info as you browse site frontend.

  • Craft Debug Toolbar - frontend toolbar with profiling info.

  • Craft Log Viewer - makes logs easier to search and analyze.

  • Xdebug - PHP debugger and profiler.

And enable these useful log files:

  • Craft logs at storage/logs

  • PHP error logs

  • Web server access and error logs

  • Debug logs for caching servers like Redis, Memcached.

These tools and logs provide valuable insights into pinpointing template issues.

Fixing Specific Issues

To address common copied template problems:

  • 500 errors - increase PHP memory limit and max execution time in php.ini.

  • CSS not loading - double check CSS file name and path references.

  • Images not loading - validate image paths defined in template are correct.

  • Broken links - fix incorrect URL references and new aliases.

  • Missing fonts/JS - check for issues with static asset references.

  • Outdated content - resave affected matrix blocks, entries, etc to trigger refresh.

  • Pagination problems - adjust template or config values around page size.

  • Performance problems - enable template caching and optimise slow queries.

With patience and a systematic process, any template copy errors can be diagnosed and fixed.

Proper tools, thorough logs, and an understanding of common issues helps get copied templates back on track quickly.

Shape April 2022 HR 202
Andy Golpys
- Author

Andy has scaled multiple businesses and is a big believer in Craft CMS as a tool that benefits both Designer, Developer and Client. 

Share
Feedback
Show us some love
Email Us
We usually reply within 72 hours
Agency Directory
Submit your agency
Affiliate Partners
Let's chat