#TSV: テンプレート展開

Overview

#TSV: テンプレート展開

translate #TSV: Expand Template

プレースホルダー(”{{0}}”, “{{1}}”, …)を含むテンプレートを使って新しいテキストを生成します。TSVの各行に対してテンプレートが適用されるため、Markdown、HTML、JSON配列、AIプロンプトなどを一括生成するのに便利です。

Auto Step icon
Configs for this Auto Step
StrConfA1
A1: 入力TSV文字列をセットしてください *#{EL}
BoolConfA2
A2: 先頭行(ヘッダ)を処理対象から外す, Off ⇔ On
StrConfB
B: テンプレートをセットしてください(A列は “{{0}}”、B列は “{{1}}”) *#{EL}
SelectConfC
C: 出力テキストが格納される複数行文字列型データを選択してください (更新) *
SelectConfD1
D1: 入力TSV行数を格納する数値型データを選択してください (更新)
SelectConfD2
D2: 入力TSV行数(空行を無視/ヘッダ含)を格納する数値型データを選択してください (更新)
SelectConfD3
D3: 出力テキストの行数を格納する数値型データを選択してください (更新)
Script (click to open)
// Script Example of Business Process Automation
// for 'engine type: 3' ("GraalJS standard mode")
// cf. 'engine type: 2' ("GraalJS Nashorn compatible mode") (renamed from "GraalJS" at 20230526)


//////// START "main()" /////////////////////////////////////////////////////////////////
main();
function main(){ 

//// == Config Retrieving / 工程コンフィグの参照 ==
const strTsv         = configs.get        ("StrConfA1")
                       .replace(/\r\n/g, "\n").replace(/\r/g, "\n");     // REQUIRED
  if( strTsv === "" ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {A1: TSV} is empty \n" );
  }
  const arr2dTsv     = parseAsRectangular ( strTsv );  // [row,col]
  if (arr2dTsv.length === 0) {
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {A1: TSV} contains no data rows \n" );
  }
const boolSkipHeader = (configs.get("BoolConfA2") === "true");
// A2: ヘッダー行をスキップする設定の取得(Toggleの戻り値は文字列 "true" / "false")
// https://questetra.zendesk.com/hc/ja/articles/360024574471-R2300-
const strTemplate    = configs.get( "StrConfB" )
                       .replace(/\r\n/g, "\n").replace(/\r/g, "\n");     // REQUIRED
  if (strTemplate === "") {
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {B: Template} is empty \n" );
  }
const strPocketC     = configs.getObject ( "SelectConfC" );   // REQUIRED
const numPocketD1    = configs.getObject ( "SelectConfD1" );  // not required
const numPocketD2    = configs.getObject ( "SelectConfD2" );  // not required
const numPocketD3    = configs.getObject ( "SelectConfD3" );  // not required




//// == Data Retrieving / ワークフローデータの参照 ==
// (Nothing. Retrieved via Expression Language in Config Retrieving)




//// == Calculating / 演算 ==
let numStartRow = 0;
if (boolSkipHeader && arr2dTsv.length > 0) {
  numStartRow = 1;
}

const arrOutputTxt = [];

// TSVの各行に対してテンプレートを適用
for (let numI = numStartRow; numI < arr2dTsv.length; numI++) {
  const arrRow = arr2dTsv[numI];
  
  // テンプレート内の {{0}}, {{1}}... を対応する列の値に置換
  const strFormattedRecord = strTemplate.replace(/\{\{(\d+)\}\}/g, function(strMatch, strNum) {
    const numIndex = parseInt(strNum, 10); 
    
    // 該当するカラムが存在すればその値を、なければ空文字を返す
    return arrRow[numIndex] !== undefined ? arrRow[numIndex] : "";
  });

  arrOutputTxt.push(strFormattedRecord);
}

// 処理結果を改行で結合
const strOutputText = arrOutputTxt.join('\n');


//// == Data Updating / ワークフローデータへの代入 ==

if ( strPocketC !== null ){ 
  engine.setData( strPocketC, strOutputText );
}
if ( numPocketD1 !== null ){ 
  engine.setData( numPocketD1, new java.math.BigDecimal( strTsv.split("\n").length ) );
}
if ( numPocketD2 !== null ){ 
  engine.setData( numPocketD2, new java.math.BigDecimal( arr2dTsv.length ) );
}
if ( numPocketD3 !== null ){ 
  const numOutputLines = strOutputText === "" ? 0 : strOutputText.split("\n").length;
  engine.setData( numPocketD3, new java.math.BigDecimal( numOutputLines ) );
}

} //////// END "main()" /////////////////////////////////////////////////////////////////

/**
 * Parses TSV string as a two-dimensional rectangular data matrix and creates a 2D array.
 * @param {string} strTsv - The input TSV string
 * @returns {Array<Array<string>>} Rectangular 2D array
 */
function parseAsRectangular( strTsv ){
  const arrTsv = strTsv.split("\n");
  let numMinWidth   = Infinity;
  let numMaxWidth   = 0;
  let numBlankLines = 0;
  
  const arrParsedRows = [];
  for( let numI = 0; numI < arrTsv.length; numI++ ){
    const strLine = arrTsv[numI];
    if( strLine === "" ){
      numBlankLines++;
      continue;
    }
    const arrCells = strLine.split("\t");
    const numLen = arrCells.length;
    if( numLen < numMinWidth ){ numMinWidth = numLen; }
    if( numLen > numMaxWidth ){ numMaxWidth = numLen; }
    arrParsedRows.push( arrCells );
  }
  
  if( numMinWidth === Infinity ){
    numMinWidth = 0;
  }
  engine.log( " AutomatedTask TsvDataCheck:" + 
              " MinWidth:" + numMinWidth +
              " MaxWidth:" + numMaxWidth +
              " Lines:" + arrTsv.length +
              " (BlankLines:" + numBlankLines + ")" );

  for( let numI = 0; numI < arrParsedRows.length; numI++ ){
    const arrRow = arrParsedRows[numI];
    while( arrRow.length < numMaxWidth ){
      arrRow.push( "" );
    }
  }
  return arrParsedRows;
}



/*
### Examples

#### ▼▼ Example 1. Generating a Markdown list / Markdownのリスト生成

TSV-Cols: `Due Date (期限) \t Task Name (タスク名) \t Status \t Assignee (担当者)`

##### Template Sample

- [{{2}}] **{{1}}**
    - 担当: {{3}}
    - 期限: {{0}}

##### Input TSV Sample

2026-07-15	要件定義書の作成	o	山田
2026-07-20	デザイン案の提出	x	佐藤

##### Output Sample

- [o] **要件定義書の作成**
    - 担当: 山田
    - 期限: 2026-07-15
- [x] **デザイン案の提出**
    - 担当: 佐藤
    - 期限: 2026-07-20


#### ▼▼ Example 2. Creating an HTML table (tr) / HTMLテーブル行(tr)の作成

TSV-Cols: `Date \t Category \t Title \t URL`

##### Template

<tr>
  <td class="date">{{0}}</td>
  <td class="badge-{{1}}">{{1}}</td>
  <td><a href="{{3}}">{{2}}</a></td>
</tr>

##### Input TSV Sample

2026-07-10	news	夏期休業のお知らせ	/news/summer-holiday
2026-07-15	update	Ver 2.0 リリース	/release/v2

##### Output Sample

<tr>
  <td class="date">2026-07-10</td>
  <td class="badge-news">news</td>
  <td><a href="/news/summer-holiday">夏期休業のお知らせ</a></td>
</tr>
<tr>
  <td class="date">2026-07-15</td>
  <td class="badge-update">update</td>
  <td><a href="/release/v2">Ver 2.0 リリース</a></td>
</tr>


#### ▼▼ Example 3. JSON objects (invalid trailing commas) / JSON オブジェクト(末尾カンマは不正)

TSV-Cols: `Item Code \t Item Name \t Price \t Stock Quantity`

##### Template

{
  "itemCode": "{{0}}",
  "itemName": "{{1}}",
  "price": {{2}},
  "stockQuantity": {{3}}
},

##### Input TSV Sample

A-001	高級キーボード	15000	35
B-012	ワイヤレスマウス	4200	120

##### Output Sample

{
  "itemCode": "A-001",
  "itemName": "高級キーボード",
  "price": 15000,
  "stockQuantity": 35
},
{
  "itemCode": "B-012",
  "itemName": "ワイヤレスマウス",
  "price": 4200,
  "stockQuantity": 120
},


#### ▼▼ Example 4. Generate SQL INSERT statements / SQL INSERT 文の作成

TSV-Cols: `Employee ID (社員ID) \t Name (氏名) \t Department Code (部署コード) \t Age (年齢)`

##### Template

`INSERT INTO m_employees (emp_id, emp_name, dept_code, age) VALUES ('{{0}}', '{{1}}', '{{2}}', {{3}});`

##### Input TSV Sample

EMP001	山田 太郎	DEV-01	28
EMP002	佐藤 花子	HR-02	32

##### Output Sample

INSERT INTO m_employees (emp_id, emp_name, dept_code, age) VALUES ('EMP001', '山田 太郎', 'DEV-01', 28);
INSERT INTO m_employees (emp_id, emp_name, dept_code, age) VALUES ('EMP002', '佐藤 花子', 'HR-02', 32);


#### ▼▼ Example 5. Reorder columns and convert to CSV-like text / 列を並べ替えてCSV風テキストに変換

TSV-Cols: `Employee ID (社員ID) \t Name (氏名) \t Age (年齢) \t Department (部署) \t Hire Date (入社日)`

##### Template

`{{0}},{{3}},{{1}}`

##### Input TSV Sample

E101	鈴木 一郎	45	営業部	2010-04-01
E102	田中 次郎	24	開発部	2024-04-01

##### Output Sample

E101,営業部,鈴木 一郎
E102,開発部,田中 次郎



### NOTES-en

* When a case reaches this [Automated Step], the text generation process is automatically executed.
    * Various texts can be generated from TSV data.
    * e.g. Markdown lists, HTML table rows, JSON object arrays, SQL statements, CSVs, etc.
    * It can be configured to treat the first row of the input TSV as a header (and ignore it during processing).
* The Template Text is applied sequentially for the number of rows in the TSV.
    * "Placeholders" (variables) within the Template Text are replaced with column data (values).
    * Placeholders are specified using 0-indexed numbers, such as `{{0}}` and `{{1}}`.
* The input TSV string is parsed as a simple tab-separated string.
    * Double quotes and other characters within the TSV string are preserved as is.
    * Blank lines within the TSV string are automatically ignored.
    * For rows with an insufficient number of cells, empty string ("") cells are automatically padded.
    * The number of input and output TSV rows can be stored as case data.

### APPENDIX-en

* If the input data contains blank lines, those lines are automatically skipped.
* If a placeholder number (e.g., the 5 in `{{5}}`) exceeds the number of columns in the TSV row, it will be treated as an empty string.
* A safe design (Mustache syntax) is adopted to prevent conflicts with currency symbols like `$100`.
    * Numeric placeholders use a Mustache-like delimiter. Values are inserted without escaping.
    * The literal `{{0}}` cannot be output. (escape syntax not supported)


### NOTES-ja

* 案件(ケース)がこの[自動工程]に到達すると、テキスト生成処理が自動実行されます。
    * TSVデータから、さまざまなテキストを生成できます。
    * Markdownリスト、HTMLテーブル行、JSONオブジェクト配列、SQL文、CSV、…
    * 入力TSVの1行目を、ヘッダー行として認識される(読み込まない)設定も可能です。
* テンプレートTextは、TSVの行の数だけ呼び出されます。
    * テンプレートText内の「プレースホルダ」(変数)が、列データ(値)に置換されます。
    * プレースホルダは、0から始まる連番を使って `{{0}}` や `{{1}}` のように指定します。
* 入力TSV文字列は、シンプルなタブ区切り文字列としてパースされます。
    * TSV文字列内のダブルクオート文字等も、そのまま保持されます。
    * TSV文字列内の空行は、無視されます。
    * TSV文字列内でセル数の足りない行は、空文字("")のセルが自動的に補完されます。
    * 入出力TSVの行数は、ケースデータとして格納可能です。

### APPENDIX-ja

* 入力データに空行が含まれている場合、その行は自動的にスキップされます。
* プレースホルダの番号(例: `{{5}}` の5)がTSVの列数より多い場合、空文字として処理されます。
* 金額などの $ 記号とは衝突しない安全な設計(Mustache記法)が採用されています。
    * 数値プレースホルダーは、Mustache 形式に似た区切り文字を使用します。値はエスケープされずに挿入されます。
    * リテラルの `{{0}}` は出力できません。(エスケープ構文はありません)

*/

Download

warning 自由改変可能な JavaScript (ECMAScript) コードです。いかなる保証もありません。
(アドオン自動工程のインストールは Professional editionでのみ可能です)

Notes

  • 案件(ケース)がこの[自動工程]に到達すると、テキスト生成処理が自動実行されます。
    • TSVデータから、さまざまなテキストを生成できます。
    • Markdownリスト、HTMLテーブル行、JSONオブジェクト配列、SQL文、CSV、…
    • 入力TSVの1行目を、ヘッダー行として認識される(読み込まない)設定も可能です。
  • テンプレートTextは、TSVの行の数だけ呼び出されます。
    • テンプレートText内の「プレースホルダ」(変数)が、列データ(値)に置換されます。
    • プレースホルダは、0から始まる連番を使って {{0}}{{1}} のように指定します。
  • 入力TSV文字列は、シンプルなタブ区切り文字列としてパースされます。
    • TSV文字列内のダブルクオート文字等も、そのまま保持されます。
    • TSV文字列内の空行は、無視されます。
    • TSV文字列内でセル数の足りない行は、空文字(””)のセルが自動的に補完されます。
    • 入出力TSVの行数は、ケースデータとして格納可能です。

Capture

Appendix

  • 入力データに空行が含まれている場合、その行は自動的にスキップされます。
  • プレースホルダの番号(例: {{5}} の5)がTSVの列数より多い場合、空文字として処理されます。
  • 金額などの $ 記号とは衝突しない安全な設計(Mustache記法)が採用されています。
    • 数値プレースホルダーは、Mustache 形式に似た区切り文字を使用します。値はエスケープされずに挿入されます。
    • リテラルの {{0}} は出力できません。(エスケープ構文はありません)

See also

Questetra Supportをもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む