How to read a text file containing html without us

2020-05-09 19:17发布

问题:

I have a text file in assets folder that contains some html to be rendered in a div on a specific component.

Is there a way to read that file and assign the contents to a string variable without user interacting with view (with input file type) in ngOnInit.

My findings If I put the html contents in json object, we will have to remove all line breaks from it. Meaning it will be a string without line breaks like this.

{
  "html": "<h1 class=\"user\">Name</h1><p>Ahsan</p>"
}

This has a limitation for designers, They will be converting html to multi-line string and we will also be removing the escape sequences.

How this can be achieved with text files.

Reasons to do this

I want to do it because, I want to avoid rebuilding and publishing me entire angular app for some content changes. Even for some content changes I have to rebuild and republish the application.

回答1:

Question is pretty vague, so I'll just list some options to look into:

1) Firstly, if this is a browser page, you can serve the html page on the server and request it from the client.

2) Alternatively, you can have a build step that replaces some variable value with the HTML file's contents. This will avoid the HTTP request of solution (1).

3) On the other hand, if this is a node (or electron) app, in addition to solution (2), you can use node's fs to access the HTML file.

4) Lastly, perhaps the simplest but least salable solution, put the HTML in a JS object. Unlike JSON, JS objects can support new lines; e.g.

let x = {
    str: `line 1
          line 2`
};

Though even if you want to use a JSON file, you could include escaped new liens \n in strings.



回答2:

An example of what you're doing or some of your existing code would help but, if I'm understanding your question correctly, you can surround your html in single quotes and it'll just be read in as a string (even if it contains double quotes). For example:

If your html is read like this:

> <button onclick="describeRob()">Tell Me about Bob!</button>
> 
> <script> function describeRob() {
>     document.getElementById("myHeader").innerHTML = "Bob constantly shows up late and doesn't understand basic programming."; } </script>

You can simply read that in as a string that can be later appended to the html of a div through javascript like so:

> String inputFromFile = ' <button onclick="describeRob()">Tell Me about Bob!</button>
> 
> <script> function describeRob() {
>     document.getElementById("myHeader").innerHTML = "Bob constantly shows up late and doesn't understand basic programming."; } </script> ';

You can then assign that string to whatever div you want, and it'll render as true HTML

If you want to throw in a line break, just put one manually in the html:

<br>