[SalesForce] How to access the html text in static resource file in lightning client-side controller

How can I access the html text in static resource file in lightning client-side controller?

I know how to upload .html file to static resources and how to acquire it using <ltng:require>, but I do not know how to access its content once it is acquired.

Best Answer

<ltng:require> is used for loading JavaScript and style sheets, not static HTML. In order to make HTML content available for your Lightning JavaScript controller, you'd need to structure your static resource as a JavaScript file that assigns HTML content to some top-level property, which you can then access in your controller and include in your component.

Alternately, you'd need to call out to your server-side Apex controller to query for the body of the StaticResource and return the data to you.

Here's an example of the former approach.

Static Resource testsr

window.myHTML = '<strong>Hello, <em>world!</em></strong>';

TestQ231776.app

<aura:application >
    <aura:attribute type="String" name="html" />
    <ltng:require scripts="{! $Resource.testsr }" afterScriptsLoaded="{!c.afterScriptsLoaded}" />
    <p>
        <aura:unescapedHtml value="{! v.html }" />
    </p>
</aura:application>

TestQ231776Controller.js

({
    afterScriptsLoaded : function(component, event, helper) {
        component.set('v.html', window.myHTML);
    }
})

TestQ231776.css

.THIS strong {
    font-weight: bold;
}

.THIS em {
    font-style: italic;
}

Result

enter image description here