You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何动态检测仅模板的Ember Glimmer组件是否存在?

Ember仅模板Glimmer组件存在性检测方案

hasRegistration('component:xxx')对仅模板Glimmer组件失效的核心原因是:仅模板Glimmer组件没有对应的JS类文件,不会在容器中注册component:前缀的条目,只有对应的模板会以template:components/为前缀完成注册。

你可以直接修改现有辅助方法的判断逻辑,同时检测组件类注册、对应模板注册两种情况,即可覆盖所有组件场景,示例代码如下:

import { getOwner } from '@ember/application';

function checkComponentExists(componentName) {
  const owner = getOwner(this);
  // 同时覆盖带JS的组件、仅模板组件两种场景
  return owner.hasRegistration(`component:${componentName}`) 
    || owner.hasRegistration(`template:components/${componentName}`);
}

注意事项

  • 嵌套层级的组件直接传入对应路径即可,比如要检测components/ui/button,传入ui/button作为参数即可,模板路径会自动匹配template:components/ui/button
  • 该方案兼容经典组件、普通Glimmer组件、仅模板Glimmer组件三种类型
  • 如果项目使用了自定义模板解析规则或者非常规目录结构,调整template:后面的路径前缀匹配项目配置即可

如果需要在模板中直接调用,可以将上述逻辑封装为Helper:

// app/helpers/component-exists.js
import { helper } from '@ember/component/helper';
import { getOwner } from '@ember/application';

export default helper(function componentExists([componentName]) {
  const owner = getOwner(this);
  return owner.hasRegistration(`component:${componentName}`) 
    || owner.hasRegistration(`template:components/${componentName}`);
});

模板中使用方式:

{{#if (component-exists "ui/button")}}
  {{component "ui/button"}}
{{/if}}

内容的提问来源于stack exchange,提问作者moondaisy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:36:03