如何在JavaScript中不使用输入类型文件的情况下读取包含html的文本文件? [英] How to read a text file containing html without using input type file in JavaScript?
问题描述
我在资产文件夹中有一个文本文件,其中包含一些要在特定组件的div中呈现的html.
I have a text file in assets folder that contains some html to be rendered in a div on a specific component.
有没有一种方法可以读取该文件并将其内容分配给字符串变量,而无需用户与ngOnInit中的视图(具有输入文件类型)进行交互.
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.
我的发现 如果我将html内容放在json对象中,我们将不得不从中删除所有换行符.这意味着它将是一个没有换行符的字符串.
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>"
}
这对设计人员是有限制的,他们将html转换为多行字符串,并且我们还将删除转义序列.
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.
这样做的原因
我想这样做是因为,我想避免为某些内容更改而重建和发布整个角度应用程序.即使是某些内容更改,我也必须重新构建并重新发布该应用程序.
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.
推荐答案
问题非常模糊,因此我只列出一些选项以供查看:
Question is pretty vague, so I'll just list some options to look into:
1)首先,如果这是浏览器页面,则可以在服务器上提供html页面并向客户端请求.
1) Firstly, if this is a browser page, you can serve the html page on the server and request it from the client.
2)或者,您可以执行一个构建步骤,用HTML文件的内容替换一些变量值.这样可以避免解决方案(1)的HTTP请求.
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)另一方面,如果这是一个节点(或电子)应用程序,则除了解决方案(2)之外,还可以使用节点的fs
访问HTML文件.
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)最后,也许是最简单但最不可行的解决方案,是将HTML放入JS对象.与JSON不同,JS对象可以支持换行.例如
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`
};
尽管即使您想使用JSON文件,也可以在字符串中包含转义的新留置权\n
.
Though even if you want to use a JSON file, you could include escaped new liens \n
in strings.
这篇关于如何在JavaScript中不使用输入类型文件的情况下读取包含html的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!