8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【javascript】ヒアドキュメント(自分用)

Last updated at Posted at 2015-04-26

他所で拾ったヒアドキュメントの書き方を関数化して
テンプレート風に使えるようにしたもの

javascript
/**
 * ヒアドキュメント実装
 * 'function(){/*' から '*/}'の間の文字列を取得する
 * オブジェクト{key:value,...}を渡せば'{@key}'をvalueに変換する
 */
function heredoc(data,func){
    var _data=null, _func=null;

    // 初期化
    if (typeof func === 'undefined') {
        _func = data;
        _data = {};
    } else {
        _func = func;
        _data = data;
    }

    // functionでなければ処理をしない
    if (typeof _func !== 'function') throw new Error(_func + " is not a function");
    if (!(_data instanceof Object && !(_data instanceof Array))) throw new Error(_data + " is not a object");

    // ヒアドキュメント本体を取得
    var _doc = _func.toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

    // dataを回して変数の置換
    for (var _key in _data){
        var _reg = new RegExp("\\{@"+_key+"\\}","g");
        var replacement = _data[_key];
        _doc = _doc.replace(_reg, replacement);
    }

    return _doc;
}

※追記

使い方

// パラメタなし
var doc = heredoc(function(){/*
<div>
  <span>HEREDOCUMENT</span>
</div>
*/})

// パラメタあり
var doc = heredoc({
  mes:"HEREDOCUMENT"
},function(){/*
<div>
  <span>{@mes}</span>
</div>
*/})

8
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?