4

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.

4

<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

  • Oh. It is a pity that it is impossible to have an .html file in static resources. So, .html templates are impossible in lightning. – hellohowdoyoudo Sep 9 '18 at 16:41
  • Well, that's overstating it a little. There are (at least) two routes to access static HTML, as above. But remember also that a Lightning component is itself something like a template. Your Lightning component markup is HTML + Lightning components. – David Reed Sep 9 '18 at 17:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.