---
title: "Demandware Script"
author: "kirenenko04"
date: "2014-07-28T10:31:24Z"
tags: []
categories: ["编程语言"]
slug: "demandware-script"
draft: false
lastmod: "2014-07-28T10:39:36Z"
id: 2097165
url: "https://kirenenko04.iteye.com/blog/2097165"
---

# []()[]()Demandware Script (DS)

 

**Overview**

 

The server-side language used for coding in the Demandware Platform is Demandware Script (DWScript).DS is based on **JavaScript**, which is standardized as **ECMAScript**.

 

**Use**: **access data** about the system, such as products, catalogs, prices.

 

**Write in**: pipelines inside **Decision nodes**, and in **ISML** templates for

 

expressions or inside **&lt;isscript&gt;** tags. But by far the **most** extensive use of DS is inside **Script pipelets**.

 

**API Packages**

 

The Demandware Script API is organized in packages just like Java.

 

However, you **cannot** **inherit** from these classes or packages when you create a script, which is indeed different from Java. You can **only** use the **properties** and **methods** of these classes in your scripts.

 

***TopLevel***  **package**

 

This is the **default** **package** in Demandware Script. It does not need to be imported in scripts. It provides standard ECMAScript classes and extensions, such as: **Error**, **Date**, **Function**, **String**, **Math**, **Number**, XML.

 

Of interest here is the **TopLevel.global** class, which contains many of the **common variables** and **constants** used in pipelines and scripts, such as:

 

**Constants**: **PIPELET\_NEXT** and **PIPELET\_ERROR**

 

These are used to indicate (表明) the **result** of a script pipelet and determine which exit the pipeline takes after pipeline execution

 

**Properties**: **customer**, **request** and **session**

 

These are commonly used in scripts to get **access to** the c**urrent customer** and the **current session**

 

**IMPORTANT NOTE**

In the following packages you will find many classes that end with the word **Mgr**, for example: **dw.catalog.ProductMgr**. The role of these classes is to retrieve instances of business objects related to the package they belong to: you use **ProductMgr.getProduct(String id)** to get **a product using a unique identifier**. The method returns a Product instance which you can use to find information about the product.

 

**Using Demandware Script in ISML**

 

Demandware Script can be embedded into ISML by using the **&lt;isscript&gt;** tag. The example code below shows how to get the **root category** of a current site’s **navigation catalog** as well as getting the category named 'sale' using Demandware script.

 

Inside of the **&lt;isscript&gt;** tag you can **fully qualify** every class you want to use or you can choose to import any packages at the top of the script:

 

&lt;isscript&gt;

 

    importPackage(dw.catalog);

 

    var siteCatalog = CatalogMgr.getSiteCatalog();

 

&lt;/isscript&gt;

 

**Script Pipelets**

Demandware Script files have an extension of **.ds** and are stored in the

**/cartridge/scripts** directory.

 

Script files like **Pipelets**, can have **input** and **output** **parameters** for data manipulation.

When you create a new script file, the file will be **preconfigured** (预配置) for scripting.

 

**Input & Output Parameters**

 

Input and output parameters are configured within the **script text**. The script text below is an example of an input parameter that is called ‘ProductID’ which takes in a **string** value while the output parameter is called ‘Product’ and returns a **product object**

 

When you first create a script file, the input and output parameters are commented out with a **\*-** so you will need to delete the **minus** sign for the Demandware application to read the parameters

 

For input/output data types, you can use **TopLevel** package classes such as **String**, **Number**, **Object**, etc. You can also specify any other data type as long as you fully qualify it: **dw.catalog.Product**. In the following snippet the TopLevel.Object data type allows you to avoid having to qualify the object you are returning:

 

@output Subscription : Object

@output Product : dw.catalog.Product **Must** fully qualify this output type

 

**Importing**

 

When working with script files, if you access Demandware Script packages or classes **other than** TopLevel, you will need to import them **in the script using the following syntax:**

importPackage ( dw.system );

 

You can import **a single class**, if you wish:

importClass( dw.system.Logger );

 

You can import a **custom script** from **the same cartridge** as the current script you are writing:

importScript( "common/libJson.ds" );

 

If you are accessing a script in **another** cartridge, make sure you specify the cartridge prior to the script name as the system will not look for further scripts with the same name in the cartridge path:

 

importScript( "&lt;cartridge name&gt;:\[folder/]utilities.ds" );

 

Of course, you can always **fully qualify** the access to a specific class and avoid importing that package/class.

 

**Using the Script Editor**

You can turn on line numbers on the script by **right-clicking** the gray column on the left side of the editor and selecting the **Show Line Numbers** checkbox

 

The editor offers **auto-complete** capabilities and syntax checking: use these tools to minimize coding errors. Studio will automatically generate code hints when you click **Ctrl+Spacebar**:

 

**Scripts and Cartridge Path Relationship**

Although script pipelets can reference scripts in the same cartridge or from dependent cartridges, scripts are **NOT** searched using the cartridge path, unlike pipelines. A script is expected to(希望) be in the cartridge of the current executing pipeline unless the cartridge is explicitly **stated in** the ScriptFile configuration property. In the figure below, the solutions cartridge, product directory (under scripts), GetProduct.ds script will be used:

虽然script pipeliets可以引用scripts在相同的cartridge, 或依赖的cartridge, scripts不是使用cartridge来搜索的，不像pipleline. 一个script希望在一个cartridge在当前执行pipeline中。除非cartridge 明确地指明在ScriptFile配置属性中，像下面这样，solutions cartridge, product 目录（在scripts下），GetProduct.ds 脚本将被使用

 

Of course, this means that you will need to add the solutions cartridge to the cartridge path so the script is found. In which order the solutions cartridge appears in the path is not relevant from the point of view of script access. However, the order of cartridges is relevant for executing pipelines and templates, in which case the first matching file found is used.

当然，这意味着你将需要添加solutions cartridge到cartridge path，这样script 才会被找到。Solution出现在path的什么位置与访问脚本无关，然而，cartridges的顺序对执行pipeline和templates有关，在这种情况下，第一个被找到的文件会被使用。

 

**The ScriptLog Output**

 

Every script **pipelet** used **in a pipeline** comes with a default Dictionary Output property called the **ScriptLog**, of type String:

You can write to the ScriptLog output within your script by using the

 

**TopLevel.global.trace**(msg : String , params : Object ...)

**method** which uses Java MessageFormat. While this capability(功能) exists in the platform as a way to write debug or error messages to the pipeline, its use is ***not*** recommended at this time. We suggest you use the **dw.system.Logger API** to write to log files instead.

 

**Script Debugging**

Studio gives you the ability to **debug scripts** as well as pipelines. In order to use a script debugger you must first create a **script debug configuration**. The process for creating a script debug configuration is identical (相同) to the pipeline debug configuration setup:

In order to **use the debug configuration** you will need to add **breakpoints** in your script files.

When debugging, it is **possible** to run the script debugger **along with** the pipeline debugger.

 

**Resource API and Resource Bundles** **（翻译功能）**

In storefront code you want to **avoid** **hard-coding** text strings that become visible to the user. Titles, labels, messages, button and field names should all be externalized by using **resource bundles** (又名properties files.). Also, if you do not want to duplicate ISML templates in order to create **locale-specific** templates, you can use resource bundles to keep your template generic and reusable.

 

A resource bundle is a file with a **.properties** extension that contains the **hard coded** strings to be used in ISML templates. In SiteGenesis bundles are loosely **named by the functional** area where the strings are used, but you can use any file name and organization you want.

 

**IMPORTANT NOTE**

Property files can be **suffixed** by “Bundlename\_&lt;&lt;locale\_id&gt;&gt;.properties”  where “&lt;&lt;locale\_id&gt;&gt;” stands for a **specific locale term** other than the default locale.

 

For example, “de” or “en”

(or locale plus country like “de\_DE” or “en\_GB”).

 

The resource bundles contain **key=value pairs** where the key might be compound 复合型key : (key.subkey) and the value is a **hard-coded** string that uses Java MessageFormat syntax to implement parameter replacement. Bundles are stored in each cartridge within the **/templates/resources** directory

 

Strings from the bundles are accessible to all ISML templates via the

 dw.web.Resource.msg(**key** : String , **bundleName** : String , **D****efaultMessage** : String ) method:

 

&lt;h1&gt; ${Resource.msg(‘**account.header**’, ‘**account’**, **null**)} &lt;/h1&gt;

 

Notice that the **second parameter** points to the **account.properties** file, which **may be overridden** by another cartridge in the cartridge path. The null in the third parameter means that the key itself will be used whenever that key is not found on any resource bundle. Instead of the null you can also show a string to display on the storefront in case the key could not be found.

 

Another useful method is the

**dw.web.Resource.msgf**(**key** : String , **bundleName** : String , **defaultMessage** : String , **args** : Object...). Using this method you can specify a key with **placeholders** which can be **dynamically replaced by** the parameters specified in the **args** argument of the method. For example, this usage of the method:

**${Resource.msgf('singleshipping.wishlist', 'checkout', null,****owners.get(addressKey).profile.firstName )}**

 

Will be paired with the following Java MessageFormat definition in the resource bundle to allow the first name of the wishlist’s owner to show up as Stefan’s Wishlist:

**singleshipping.wishlist={0}\\'\\'s Wishlist**