I can't seem to figure out how to include a file using Node.js. All of the other questions seem to discuss including other JS files, but I'm looking for the equivalent of a PHP include (files that can contain HTML content).
Usually in PHP, my view files like this:
...stuff
<?php include 'header.php'; ?>
<?php include 'nav.php'; ?>
... more stuff
<?php include 'footer.php'; ?>
And for example in nav.php I have:
<nav role=navigation>
<ul>
<!-- links -->
</ul>
</nav>
Is there similar functionality in Node or do I have to change my way of developing web applications? I am using the Express framework if that helps.
A short, working example would be highly appreciated.
No, that isn't the way nodeJS is working. If you like to compare, compare nodejs to ruby or ASP.NET. There is jade, as dystroy said, but if you are familiar with HTML syntax prefer ectjs for example :
stuff...
<div id="content">stuff</div>
<% include 'footer.ect' %>
Of course, if there is code to include use require
There's nothing similar directly into nodejs.
But many people using nodejs also use a framework like express and template engines.
For example Jade lets you do includes :
index.jade file :
doctype html
html
include includes/head
body
h1 My Site
p Welcome to my super lame site.
include includes/foot
includes/head.jade file :
head
title My Site
script(src='/javascripts/jquery.js')
script(src='/javascripts/app.js')
includes/foot.jade file :
#footer
p Copyright (c) foobar
It should be noted that in the age of ajax, single page applications and javascript, template includes are much rarely needed that in the old times of PHP. You might want to first play a little with templates (for example using Jade) and only after decide if you need includes.
You can user vash engine. Take for example this layout page:
<body>
<!-- Body content -->
<div>#html.block("body")</div>
<!-- Render Page Specific Scripts Here -->
#html.block("scripts")
</body>
Now in your other views, you can do smth like this:
#html.extend("layout", function(model){
<!-- main content of the page -->
#html.block("body",function(model){
<h1>This will be the login page</h1>
})
<!-- page specific scripts -->
#html.block("scripts",function(model){
<scrip></script>
})
})
Hope this helps!
let's assume we have to include 2 files inside index.html
the simplest way
html index.html
<%include filename.extension%>
<%include anotherfile.html%>
node.js
var temp = require('templatesjs');
// ... ... ...
fs.readFile("./index.html"){
if(err) throw err;
var output = temp.set(data);
res.write(output);
res.end();
});
those two file will get included inside index.html automatically when you use set()
i have used module templatesjs
$ npm install templatesjs
a good documentation here
github : templatesjs
Related
I'm very new to html and CSS, been learning on the go to update a website.
I understand how you can use CSS to store styles so that you can apply styles to multiple elements/pages with ease, and changing the attributes in a CSS style will automatically change all the html styles it governs across multiple pages.
I was wondering if you are able to do this somehow with actual html content instead of just style attributes.
Example: We have heaps of project pages, at the end of every project page we have a table with a bio of the manager who ran the project. This html code is manually written into every page. Since it is manually written though, if you ever want to change or update the info in bio table, you will have to go through and manually update it on every page. Is there a way to have the info in the bio table stored in something similar to a CSS stylesheet, so it just links to every page, and updating the info in the stylesheet will automatically update the info on every page it is linked in.
Code something like:
CSS
.personAbio {
<table><tr><td>Name</td>
<td>Sales Last Week</td></tr>
<tr><td>John</td>
<td>$100</td></tr>
</table>
}
Html
<table class="personAbio">
</table>
There are several ways to accomplish what you need.
Statically include content
The first way is by using (as already suggested) some server-side language.
Using PHP it's simple as, say we're inside your project_8.php (notice the PHP extension!) you simply place this PHP code where you want the about content to appear:
<?php include "about.html"; ?>
Dynamically include content
There's also a dynamic way to accomplish the same using JavaScript and AJAX.
For sake of simplicity hers's how it's done using the jQuery library:
<div id="hereGoesTheAbout"></div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$("#hereGoesTheAbout").load("about.html");
</script>
The above two <script> tags are best placed right before the closing </body> tag.
Including content dynamically is crawlable by Googlebot, just, a small penalty is given (over the static implementation) - since the additional requests to retrieve the content.
The difference is that using a server-side technique the content is found and embedded into a page while still on the server.
Using JavaScript and AJAX (like in the example above) the page arrives to your browser and than JavaScript dynamically sends to the server a request for the desired content to include.
Not a good way to insert content is by using <iframe>. It's terribly complicated (and involves lot of JS and messaging techniques) to make it responsive.
Also search engines will not index such content so it's not good for your page SEO.
Winner
Static include. Using the same technique you can split your website architecture into manageable includes.
Say you have some product.php template page, and you have all your products inside a folder products/ as files like 000.html to 999.html.
By just linking to example.com/product.php?pr=233 you can get your 233.html product:
<?php include "header.html"; ?>
<article>
<h2>Product:</h2>
<?php include "products/{$_GET['pr']}.html"; ?>
</article>
<aside>
<?php include "about.html"; ?>
</aside>
<?php include "footer.html"; ?>
with the above what you have:
one product.php file template (for all your products)
only one header.html file
only one footer.html file
only one author file
one products/ folder with all your nnn.html products contents.
You are looking for a back end coding language like PHP.
No you can't.
But you can use JavaScript instead to store your data and then bind them into the table.
For exemple:
html:
<table class="personaBio">
<thead>
<tr>Name<\tr>
<tr>Sale of the last week</tr>
</thead>
<tbody></tbody>
</table>
JavaScript/JQuery
var persons = [{name:'John', saleLastWeek:'100'}];
persons.forEach(function(person) {
$('tbody').append(`<tr><td>${person.name}</td><td>${person.saleLastWeek}</td></tr>`);
}
This is an exemple, I am on my phone, I didn't try this code.
You need to learn JavaScript or Jquery.
As already mentioned, you can do it server-side, using a number of approaches:
Server-side includes
Any server-side language/frameworks: PHP, Ruby, Python, Java, etc.
You can, however, also do it on the client side:
With <iframe>: <iframe src="managers/john.html">
With Javascript:
Put all manager bios into, say, manager-bios.js:
var managerBios = {
"john" : { "fullName": "John Doe", "projects": ["a", "b", "c"] ...}
"jane" : ....
}
Reference it in the html: <script src="manager-bios.js"
Reference corresponding manager on the page: <div id="responsibleManager" data-manager="john">
On page load, populate manager's data (I'm using jQuery here):
$(document).load(function() {
var managerId = $("#responsibleManager").data("manager");
$("#responsibleManager").html("<div>" + managerBios[managerId].fullName + "</div> Projects: " + managerBios[managerId].projects.join(","));
}
Load data from external source with Javascript (again, using jQuery here, assuming same html as above):
$("#responsibleManager").load("managers/" + $("#responsibleManager").data("manager") + ".html");
Let's say I have a element in foo.html. How can I import and embed it in another HTML file?
Have you tried using jQuery .load ?
So in another.html you would have:
<div id="place-to-embed-element"></div>
<script>
$( "#place-to-embed-element" ).load( "foo.html #imported-id" );
</script>
Hope this helps!
Okay ... that sounds odd. What do you mean by "importing"? HTML is a mark-up language, not a "real" programming language like PHP etc., so this functionality is, of course, not given by default. You could start to write PHP or juse JavaScript ... or just explain your question more detailed ;)
(Or just copy your html segment into the other file ]:-> )
maybe use php...
rename your file from 'file.html' to 'file.php' and copy this into it:
<?php
include("foo.html");
?>
This question already has answers here:
What are the new frames? [closed]
(3 answers)
Closed 7 years ago.
I've been asked to develop some simple views for an e-commerce website, but I can not use any framework, just raw HTML and CSS. My problem is that I do not want to repeat the navigation bar and footer code in each view. I am used to developing with Ruby on Rails, where I can solve this issue using partials.
Is there anything similar for this case or do I have to include the same code in each view (just because HTML is a static language)?
Thanks in advanced
This is where it can be useful to have a build script like gulp. Generally the process for things like static web pages is using a templating language like Jade or Handlebars. With Jade, you could just write something like this:
html
body
include ./includes/header.jade
Then compile it using gulp
var jade = require('gulp-jade');
gulp.task('templates', function() {
var YOUR_LOCALS = {};
gulp.src('./lib/*.jade')
.pipe(jade({
locals: YOUR_LOCALS
}))
.pipe(gulp.dest('./dist/'))
});
Other than a build step, however, there is no way to repeat static content using pure HTML and CSS.
You can create a separate footer and header html file then include them on your pages using php include like this <?php include 'header.html';?> and <?php include 'footer.html';?>
Just and them inline your main.html page wherever you want to add them.
or you can use Jquery like this:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("footer.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
I know a trick to make link to article without template (tmpl=component), but I see that it still links some styles:
index.php?option=com_content&view=article&id=171:uvjeti-plaćanja&catid=19:poliklinika&Itemid=101&tmpl=component
Is it possible to create link to just bare bones data you'd see in content editor for example?
It would be prefferable if nothing else but pure article content is returned. No html, body, head ... tags.
I have ended up creating file raw.php which contains following code:
<?php defined( '_JEXEC' ) or die( 'Restricted access' );?><jdoc:include type="component" />
I have placed this into my template folder and I can just call it with following url:
/?option=com_content&view=article&id=171&catid=19&Itemid=101&tmpl=raw
Analog to that you one can make new.php, place it to folder of current template in use and call it with &tmpl=new argument.
I am learning html, css and content management by building my own personal site, but I have very little experience in any of these areas. One thing that has bothered me is the amount I have to repeat a segment of "html code". For example, on my site I may have a block that looks like:
<div class="talk">
<a href="link">
title
<div class="info">
subtext
</div>
</a>
</div>
where link, title and subtext are the only elements that change. As a programmer, this looks like a function with three arguments: talk(link, title, subtext) and I would implement this by keeping a separate text file or database with all the entries and a program to "compile" the data and the HTML formatting into a final product. In fact, this is what I do now with a simple python script and BeautifulSoup. I have a feeling though, that there are tools out there for exactly this sort of thing, but there are so many options and systems I not even sure what I'm looking for exactly (Grunt, bower, Ruby on Rails, SASS, HMAL, handlebars, ...). This is not a request for recommendations, an acceptable answer could involve any framework, but I prefer simplicity over power.
What is canonical/standard way to do this? What is a minimal working example using my code block above?
Since you asked for a live example, here is one in PHP:
news_print.php
function output_some_news ($link, $title, $subtext)
{
echo
"<div class='talk'>
<a href='$link'>
$title
<div class='info'>
$subtext
</div>
</a>
</div>";
}
// this is just for show. Usually the data come from a database or data file
$topics = array (
array ("http://celebslife.com", "Breaking news", "Justin Bieber just grew a second neuron"),
array ("http://nerds.org" , "New CSS draft available", "We won't be forced to use idiotic lists to implement menus in a foreseeable future"));
function output_news ($topics)
{
foreach ($topics as $topic)
{
output_some_news ($topic[0], $topic[1], $topic[2]);
}
}
And from within your HTML page:
news.php
<?php include 'news_print.php'; ?>
<div class='news'>
<?php output_news($topics); ?>
</div>
As for using PHP as a preprocessor, it is pretty straightforward:
C:\dev\php\news> php news.php > news.html
will produce pure HTML from your PHP script.
The PHP engine will be invoked from the command line instead of a web server, and its output will be stored in a file instead of being sent back to a browser, that's all.
Of course you will have some differences. For instance, all the web-specific informations like caller URL, cookies, etc. will not be available if you use PHP offline. On the other hand, you will be able to use command line arguments and environment variables.