Eu tenho 2 arquivos HTML, suponha a.html
e b.html
. Em a.html' quero incluir
b.html'.
No JSF eu posso fazer isso assim:
<ui:include src="b.xhtml" />
Isso significa que dentro do arquivo a.xhtml
, eu posso incluir b.xhtml
.
Como podemos fazer isso no arquivo `*.html'?
Na minha opinião, a melhor solução usa jQuery:
a.html
:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html':
<p>This is my include file</p>
Este método é uma solução simples e limpa para o meu problema.
A documentação jQuery .load()
é aqui.
A minha solução é semelhante à do lolo acima. Entretanto, eu inseri o código HTML via JavaScript's document.write ao invés de usar jQuery:
a.html:
<html>
<body>
<h1>Put your HTML content before insertion of b.js.</h1>
...
<script src="b.js"></script>
...
<p>And whatever content you want afterwards.</p>
</body>
</html>
b.js:
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');
A razão para eu não usar jQuery é que jQuery.js é ~90kb em tamanho, e eu quero manter a quantidade de dados para carregar o menor possível.
Para obter o ficheiro Javascript que escapou correctamente sem muito trabalho, pode usar o seguinte comando sed:
sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html
Ou simplesmente utilize o seguinte roteiro de bash publicado como um Gist no Github, que automatiza todo o trabalho necessário, convertendo b.html' para
b.js':
https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6
Créditos para Greg Minshall pelo comando sed melhorado que também escapa a cortes nas costas e citações simples, que o meu comando sed original não considerou.
Alternativamente para navegadores que suportam [modelos literais] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), o seguinte também funciona:
b.js:
document.write(`
<h1>Add your HTML code here</h1>
<p>Notice, you do not have to escape LF's with a '\',
like demonstrated in the above code listing.
</p>
`);
Como alternativa, se você tiver acesso ao arquivo .htaccess no seu servidor, você pode adicionar uma diretiva simples que permitirá que o php seja interpretado em arquivos terminados em extensão .html.
RemoveHandler .html
AddType application/x-httpd-php .php .html
Agora você pode usar um simples script de php para incluir outros arquivos, como por exemplo:
<?php include('b.html'); ?>