``模板语法 - 优雅的降级

Jos*_*iah 1 javascript ecmascript-6

新的JavaScript模板语法很棒.超级可读和强大.我想开始使用它.

我试过这个模板:

function addGalleryItem(imageData, file) { 
    try {
        var template = `
            <section class="imageGalleryItem">
                <img src="${imageData}"/>
                <div class="itemTools" id="${file.name}">
                    <input type="text" class="description" name="description" placeholder="Description"/> <br />
                    <input type="button" name="mainImage" value="Main Image" onclick="makeMain(this)"/>
                    <input type="button" name="remove" value="Remove" onclick="removeImage(this)"/>
                </div>
            </section>
        `;
    } catch { 
        var template = '<section class="imageGalleryItem">' +
            '   <img src="' + imageData + '" />' +
            '   <div class="itemTools" id="' + file.name + '">' +
            '       <input type="text" class="description" name="description" placeholder="Description"/>'+
            '       <br />' +
            '       <input type="button" name="mainImage" value="Main Image" onclick="makeMain(this)"/>' +
            '       <input type="button" name="remove" value="Remove" onclick="removeImage(this)"/>' +
            '   </div>' +
            '</section> ';
    }

    $('#imageGallery').append(template);

}
Run Code Online (Sandbox Code Playgroud)

但亲爱的IE因为反引号(`)而对语法错误发出嘎嘎声.MSDN关于这个主题的文章包含了Edge的精彩内容,并没有提到如何为IE做些什么.

有没有办法直接将新模板语法用于生产用途?还是我们陷入困境?

Mic*_*ski 6

您不能使用try ... catch语句来捕获语法错误,因为它们甚至在代码执行之前就被抛出了.

您必须放弃对不支持模板文字或使用Babel的浏览器的支持.