ES6 tagged templates practical usability

前端 未结 3 2042
时光取名叫无心
时光取名叫无心 2020-11-27 21:24

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 jQuer

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 21:50

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

    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.

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

提交回复
热议问题