ES6 标记模板的实用性 [英] ES6 tagged templates practical usability

查看:17
本文介绍了ES6 标记模板的实用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 ES6 的语法 标记模板.我没有看到的是实际可用性.什么时候它比传递对象参数更好,比如 jQuery 的 AJAX 中的设置?$.ajax('url', {/*这个人在这里*/})

I understand the syntax of ES6 tagged templates. What I don't see is the practical usability. When is it better than passing an object parameter, like the settings in jQuery's AJAX? $.ajax('url', { /*this guy here*/ })

现在我只看到棘手的语法,但我不明白为什么我需要/使用它.我还发现 TypeScript 团队选择在其他重要功能之前实现它(在 1.5 中).标记字符串模板背后的概念是什么?

Right now I only see the tricky syntax but I don't see why I would need/use it. I also found that the TypeScript team chose to implement it (in 1.5) before other important features. What is the concept behind tagged string templates?

推荐答案

您可以使用标记模板来构建比常规函数调用更具表现力的 API.

You can use tagged templates to build APIs that are more expressive than regular function calls.

例如,我正在开发用于 SQL 查询的 proof-of-concept 库JS 数组:

For example, I'm working on a proof-of-concept library for SQL queries on JS arrays:

let admins = sql`SELECT name, id FROM ${users} 
                 WHERE ${user => user.roles.indexOf('admin') >= 0}`

注意它与字符串插值无关;它使用标记模板来提高可读性.很难用普通的函数调用来构建直观的东西 - 我猜你会有这样的东西:

Notice it has nothing to do with String interpolation; it uses tagged templates for readability. It would be hard to construct something that reads as intuitively with plain function calls - I guess you'd have something like this:

let admins = sql("SELECT name, id FROM $users WHERE $filter",
  { $users: users, $filter: (user) => user.roles.contains('admin') })

这个例子只是一个有趣的副项目,但我认为它展示了标记模板的一些好处.

This example is just a fun side project, but I think it shows some of the benefits of tagged templates.

另一个可能更明显的例子是 i18n - 标记模板可以插入您的输入的区域设置敏感版本.

Another example, maybe more obvious, is i18n - a tagged template could insert locale-sensitive versions of your input.

这篇关于ES6 标记模板的实用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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