다양한 프레임 워크에서 쿼리 바인딩을 할 때 콜론(:)을 사용하기 때문에 여기도 사용하였다
변환하려는 키(key)에 앞, 뒤로 하나씩 추가해주면 된다
:key:
자바스크립트는 예전 부터 문자에 변수 넣거나 HTML으로 이루어진 문자열에 변수 넣는 게 썩 맘에 안 들었다.
+ 기호를 써가며 합치다 보면 코드 가독성이 좋지 않고 IDE 가 아닌 텍스트 에디터를 쓴다면 더욱더 헬게이트..
그나마 최근엔 변수를 편하게 넣을 수 있는 기능이 생겨 좋지만 Template literals 해당 기능이 생기기 전까지는
마치 많은 프레임 워크에서 지원하는 것처럼 쿼리 바인딩하듯 데이터를 넣고 싶어서 만든 기능이다.
💻 사용법 How to use
let in_html = '<option class="sel_opt_p product_id_:product_id:" data-apt-id=":ad_pd_type_id:" data-short-nm=":ad_pd_type_short_nm:" value=":product_id:">옵션</option>';
let product = htmlBind(in_html, {
ad_pd_type_id:3
, ad_pd_type_short_nm:'이름'
, product_id:4
});
console.log(product);
// 결과
// <option class="sel_opt_p product_id_4" data-apt-id="3" data-short-nm="이름" value="4">옵션</option>
🎈 결과
<option class="sel_opt_p product_id_4" data-apt-id="3" data-short-nm="이름" value="4">옵션</option>
💻 코드 Code
/**
* String (HTML) 바인딩
* Sql 의 Query Binding 처럼 사용 하기 위한 코드
* @param {string} _html
* @param {object} _bind
* @returns {*}
*/
function htmlBind(_html, _bind){
_html = (!_html ? '' : _html);
_bind = (!_bind ? {} : _bind);
if( _html == '' || _bind.length == 0 ){
return '';
}
$.each(_bind, function(in_code, in_value){
if( typeof in_value == 'undefined' || typeof in_value == 'null' || in_value == null ){
in_value = '';
}
in_value = String(in_value);
in_value = html_escape(in_value);
let regex = new RegExp(":" + in_code + ":", "g");
_html = _html.replace(regex, in_value);
})
return _html;
}
💻 추가 필요 코드 Code
2022.07.07 - [javascript] - [jQuery] 엔티티 코드 변환 / entity mapping escape
/**
* 엔티티 코드 매핑을 위한 변수
* @type {{"`": string, "\"": string, "&": string, "'": string, "<": string, "=": string, ">": string, "/": string}}
*/
let entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
/**
* 엔티티 코드를 변환 한다
* @param str
* @returns {*}
*/
function html_escape(str){
$.each(entityMap, function(_key, _value){
str = str.split(_key).join(_value);
});
return str;
};