自定义卡片
仪表板 是我们为 Home Assistant 定义用户界面的方法。我们提供了许多内置卡片,但你不仅限于我们决定在 Home Assistant 中包含的那些。你可以构建并使用你自己的卡片!
定义你的卡片
这是一个基本示例,展示了可能的功能。
在你的 Home Assistant 配置目录中创建一个新文件,路径为 <config>/www/content-card-example.js
,并放入以下内容:
class ContentCardExample extends HTMLElement {
// 每当状态发生变化时,都会设置一个新的 `hass` 对象。使用这个来
// 更新你的内容。
set hass(hass) {
// 如果内容还不存在则初始化内容。
if (!this.content) {
this.innerHTML = `
<ha-card header="示例卡片">
<div class="card-content"></div>
</ha-card>
`;
this.content = this.querySelector("div");
}
const entityId = this.config.entity;
const state = hass.states[entityId];
const stateStr = state ? state.state : "不可用";
this.content.innerHTML = `
${entityId} 的状态是 ${stateStr}!
<br><br>
<img src="http://via.placeholder.com/350x150">
`;
}
// 用户提供的配置。如果抛出异常,Home Assistant
// 将会渲染一个错误卡片。
setConfig(config) {
if (!config.entity) {
throw new Error("你需要定义一个实体");
}
this.config = config;
}
// 卡片的高度。Home Assistant 使用这个来自动
// 在砖石视图中分配所有卡片到可用列中。
getCardSize() {
return 3;
}
// 在节视图中卡片在网格中的大小规则
getGridOptions() {
return {
rows: 3,
columns: 6,
min_rows: 3,
max_rows: 3,
};
}
}
customElements.define("content-card-example", ContentCardExample);