如何在Alexa/Jovo中按设备类型,指定仅渲染单个Render Document?
解决Jovo中Alexa多Directives的设备适配问题
要实现你的需求,核心是根据设备是否支持APL,动态调整Alexa响应中的directives数组,并控制聊天字幕的显示。之前的写法存在参数传递错误或语法问题,下面提供两种可行方案:
方案一:在DemoOutput内部封装设备判断逻辑(推荐)
将设备适配逻辑直接放在DemoOutput的build方法中,利用Jovo内置的this.$device上下文判断设备能力,这样Intent中只需简单调用发送指令,代码更简洁:
import { BaseOutput, AlexaCapability } from '@jovotech/framework'; export interface DemoOutputOptions {} export class DemoOutput extends BaseOutput<DemoOutputOptions> { build(): OutputTemplate | OutputTemplate[] { // 定义你的APL和APLA指令内容 const aplDirective = { type: 'Alexa.Presentation.APL.RenderDocument', // 补充你的APL文档、数据源等配置 document: {}, datasources: {} }; const aplaDirective = { type: 'Alexa.Presentation.APLA.RenderDocument', // 补充你的APLA文档配置 document: {} }; // 聊天字幕文本 const subtitleText = '这里是需要显示的聊天字幕内容'; let directives: any[] = []; let outputSpeech: any; if (this.$device.supports(AlexaCapability.Apl)) { // 支持APL的设备:返回APL+APLA指令,不显示字幕 directives = [aplDirective, aplaDirective]; } else { // 不支持APL的设备:仅返回APLA指令,同时设置outputSpeech作为字幕 directives = [aplaDirective]; outputSpeech = { type: 'PlainText', text: subtitleText }; } return { platforms: { alexa: { nativeResponse: { response: { directives, // 仅当需要字幕时才添加outputSpeech字段 ...(outputSpeech && { outputSpeech }) } } } } }; } }
在Intent中调用时只需一行代码:
return this.$send(DemoOutput);
方案二:在Intent中传递参数控制Output生成
如果需要在Intent层控制逻辑,可以通过自定义Options参数传递给DemoOutput,让Output根据参数生成对应响应:
第一步:定义DemoOutput的Options接口
export interface DemoOutputOptions { includeApl?: boolean; showSubtitle?: boolean; } export class DemoOutput extends BaseOutput<DemoOutputOptions> { build(): OutputTemplate | OutputTemplate[] { // 读取传入的参数,默认值为true和false const { includeApl = true, showSubtitle = false } = this.options; const aplDirective = { /* APL指令内容 */ }; const aplaDirective = { /* APLA指令内容 */ }; const subtitleText = '聊天字幕内容'; let directives: any[] = [aplaDirective]; let outputSpeech: any; if (includeApl) { // 添加APL指令到数组开头 directives.unshift(aplDirective); } if (showSubtitle) { outputSpeech = { type: 'PlainText', text: subtitleText }; } return { platforms: { alexa: { nativeResponse: { response: { directives, ...(outputSpeech && { outputSpeech }) } } } } }; } }
第二步:在Intent中根据设备能力传参
import { AlexaCapability } from '@jovotech/framework'; // ... if (this.$device.supports(AlexaCapability.Apl)) { return this.$send(DemoOutput, { includeApl: true, showSubtitle: false }); } else { return this.$send(DemoOutput, { includeApl: false, showSubtitle: true }); }
之前写法的问题说明
- 第一种写法中
{ message: directives[0] }无效:DemoOutput的Options未定义message参数,且无法通过这种方式修改nativeResponse中的directives数组。 - 第二种写法存在语法错误:
DemoOutput.build().return不符合TypeScript语法,且不能在$send的参数中直接修改Output的构建结果。
内容的提问来源于stack exchange,提问作者Sophie Obomighie
相关产品推荐
相关产品推荐

