Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

是否可以支持自定义的异步函数? #653

Open
skybosi opened this issue Jul 24, 2024 · 0 comments
Open

是否可以支持自定义的异步函数? #653

skybosi opened this issue Jul 24, 2024 · 0 comments

Comments

@skybosi
Copy link

skybosi commented Jul 24, 2024

我希望实现一个json5的配置,但是,我希望里面有些数据是来自网络请求的,所以需要结合art-template的功能来实现。这个时候就需要art-template实现自定义函数功能,

{
      "data": {
        "list": [
          {{ each getData('https://jsonplaceholder.typicode.com/todos') }}
            {{$value}}
          {{/each}}
        ]
      }
}

具体demo 代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Art-Template 示例</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/template-web.min.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
  <script>
    // 定义自定义函数
    template.defaults.imports.getData = async function (url) {
      try {
        const response = await axios.get(url);
        console.log(response)
        return response.data;
      } catch (error) {
        console.error(`获取数据出错: ${error}`);
        return [];
      }
    };
    // 渲染模板
    const result = template.render(`{
      "data": {
        "list": [
          {{ each getData('https://jsonplaceholder.typicode.com/todos') }}
            {{$index}}
          {{/each}}
        ]
      }
    }`);

    // 输出结果
    console.log(result);
  </script>
</body>

</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant