问题描述
我正在使用LWC框架来开发组件。它基于ES6 Standard。我正在尝试使用XSLTProcessor来满足我的要求之一,但这给我一个错误。
代码:
import { LightningElement } from 'lwc';
export default class displayReport extends LightningElement {
handleOnClick(){
if(window.XSLTProcessor){
console.log('XSLTProcessor TRUE')// Working
try
{
var xsltProcessor = new window.XSLTProcessor();
console.log('XSLTProcessor WORKING') // Not coming here
}
catch(e){
console.log(e.message); //Error displayed
}
}
if(window.DOMParser){
console.log('DOMParser TRUE')
try
{
var parser = new window.DOMParser();
console.log('DOMParser WORKING') //This is working
}
catch(e){
console.log(e.message); //No Errors
}
}
}
}
我不确定为什么XSLTProcessor
不起作用,但是DOMParser
起作用。
解决方法
在https://developer.salesforce.com/docs/component-library/tools/playground,对我来说,例如my-button.html
为
<template>
<div>
<input type="button" value="test" onclick={handleClick}>
<div class="xslt-output" lwc:dom="manual"></div>
</div>
</template>
和my-button.js
为
import { LightningElement } from 'lwc';
export default class MyButton extends LightningElement {
handleClick() {
const xsltProc = new XSLTProcessor();
const xsltCode = `<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" indent="yes"/>
<xsl:template match="list">
<section>
<h2>XSLTProcessor test</h2>
<ul style="list-style-type: disc;">
<xsl:apply-templates/>
</ul>
</section>
</xsl:template>
<xsl:template match="item">
<li>
<xsl:apply-templates/>
</li>
</xsl:template>
</xsl:stylesheet>`;
const xmlCode = `<list>
<item>foo</item>
<item>bar</item>
</list>`;
const domParser = new DOMParser();
const xsltDoc = domParser.parseFromString(xsltCode,'application/xml');
const xmlDoc = domParser.parseFromString(xmlCode,'application/xml');
xsltProc.importStylesheet(xsltDoc);
const container = this.template.querySelector('div.xslt-output');
container.appendChild(xsltProc.transformToFragment(xmlDoc,container.ownerDocument));
}
}
然后在app.html
内部,我可以使用<c-my-button></c-my-button>
,然后单击按钮,将执行XSLT并插入其结果。