``模板语法-优雅降级 [英] `` Template Syntax - Graceful Degredation

查看:60
本文介绍了``模板语法-优雅降级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的javascript模板语法很棒.超级可读且功能强大.我想开始使用它.

The new javascript template syntax is great. Super readable and powerful. I'd like to start using it.

我尝试了此模板:

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);

}

但是亲爱的IE由于反引号(`)引起语法错误. MSDN关于该主题的文章令人赞叹Edge,并且没有提到要为IE做些什么.

But dear IE squawks about a syntax error because of the backticks (`). MSDN's article on the subject totes the awesomeness of Edge and doesn't mention what to do for IE.

今天有没有办法将新模板语法直接用于生产?还是我们被卡住了?

Is there a way to use the new template syntax directly for production use today? Or are we stuck transpiling?

推荐答案

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

You can't use try...catch statement to catch syntax errors, because they are thrown even before the code is executed.

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

You either have to drop support for browsers which doesn't support template literals or use Babel.

这篇关于``模板语法-优雅降级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆