This script works perfectly apart from one aspect: it doesn’t loop through layers that are nested within folders. I’ve tried changing layers
to layerSets
as per this question, but then it stops working on folder names. I’m using Photoshop 2020 on Mac Catalina.
// JavaScript Document
var doc = app.activeDocument;
// name indexed object
var layernames = {
'Products':'Working',
'Product':'Working',
'Notes':'Note',
'Background color':'Background Colour',
'White background':'White Background'
};
// loop through all layers
for (var i = 0; i < doc.layers.length; i++)
{
//Set up Variable to access layer name
var currentLayer = app.activeDocument.layers;
if (layernames[currentLayer.name]) {
currentLayer.name = layernames[currentLayer.name];
}
}
2
Answers
From what I understand from the doc (https://www.adobe.com/content/dam/acom/en/devnet/photoshop/pdfs/photoshop-scripting-guide-2020.pdf), layers may contain ArtLayers or LayerSets.
The LayerSets contain other nested layers…
You could create a function to rename every Layer (what you did), but when it encounters a LayerSet, also recursively call the function on
currentLayer.layers
.To know if a specific Layer is a LayerSet, try
if (currentLayer.layers) ...
.Consider the following solution that utilizes a recursive function called
renameLayers
to traverse all layer nodes in the document layers tree structure.A layers
typename
property may be set to eitherArtLayer
orLayerSet
. Essentially when a layerstypename
is aLayerSet
(i.e. a Folder) we recursively call the function again.Usage Notes:
As you can see in the last line of code (above) we invoke the
renameLayers
function as follows:Here we pass in the
doc
variable, i.e. a reference to the document to change, and thelayerNames
object that defines the mappings for the original layer name and the new layer name.Running the code shown above (as is) will rename any layer in accordance with the mappings specified in the
layerNames
object. However it currently does not rename any Text Layer(s) or LayerSet(s).How can I also rename Text Layers and/or LayerSets?
The
renameLayers
function lists a third optional parameter, namedoptions
to allow a custom configuration to be defined.The following three function invocations demonstrate how different configurations can be achieved by passing in the optional
options
argument:Invoking the function as follows with
includeLayerSets
set totrue
renames LayerSets too:Invoking the function as follows with
includeTextLayers
set totrue
renames Text Layers too:Invoking the function as follows with
includeLayerSets
andincludeTextLayers
set totrue
renames both LayerSets and Text Layers too: