Is there any way to create a similar idea as master/content page in ASP.NET in pure HTML?
I want to create several pages in HTML, but I want that all of them look the same with some contents different. Is there any way to do this without creating several pages which are very similar to each other?
//wait until the dom is loaded
$(document).ready(function () {
//adds menu.html content into any "#menu" element
$('#menu').load('menu.html');
});
In reference to some of the other answers, iframes should be used carefully and sparingly.
http://rev.iew.me/help-moving-from-iframes
http://fsvieira.com/2013/06/11/iframes-bad-for-a-website/
Duplicate question here with answer: How to create a master page using HTML?
The simple way to do that is to use server side includes or SSI. However easier and, probably, much better solution would be usage of PHP with includes. This way you will always have additional PHP functionality then you need it. But both of this solutions require server that will preprocess the pages. If you want collection of pages, say, on a local hard drive, then only solution I know is already proposed iframe tag.
You can use iframe. That would be purely html.
I resolved with a Third party c# form application.
Header and footer different page
insert key to all other page. (###footer###)
Replace files contents with form Application.
footer.html
<h2>this place is footer.</h2>
default.html
<h1>Default page</h1>
bla bla bla
###footer###
Result default.html
<h1>Default page</h1>
bla bla bla
<h2>this place is footer.</h2>
Source Code below
List list = new List();
private void sourceBtn_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog(this);
if (result == DialogResult.OK)
{
sourceTxt.Text = openFileDialog1.FileName;
}
}
private void fileListSelect_Click(object sender, EventArgs e)
{
var result = openFileDialog2.ShowDialog(this);
if (result == DialogResult.OK)
{
fileList.Items.AddRange(openFileDialog2.FileNames);
}
}
private void addSourceBtn_Click(object sender, EventArgs e)
{
list.Add(new sourceKey() { filename = sourceTxt.Text, key = keyTxt.Text });
sourceTxt.Clear();
keyTxt.Clear();
sourceTxt.Focus();
sourceList.DataSource = null;
sourceList.DataSource = list;
}
private void ConvertBtn_Click(object sender, EventArgs e)
{
foreach (var filename in fileList.Items)
{
string text = File.ReadAllText(filename.ToString());
foreach (var item in sourceList.DataSource as List)
{
text = text.Replace(item.key, File.ReadAllText(item.filename));
}
File.WriteAllText(filename.ToString(), text);
}
infoLabel.Text = "Done";
}
Source Code Download Link
Use javascript gulp tool
and it will be like this :
##include('./header.html')
<!-- Content -->
<section>
<h1>Hello world</h1>
</section>
##include('./footer.html')
One of the best ways to have the option of including repeating blocks is using Gulp.js and some packages . gulp is a popular javascript toolkit to automate & enhance your workflow .
for using it first install gulp in your project using yarn or npm :
yarn init
Install the gulp-file-include plugin :
yarn add gulp gulp-file-include -D
create gulpfile to be able to create tasks with Gulp
In linux :
touch gulpfile.js
if you are using windows use this command instead :
type "gulpfile.js"
In the gulpfile.js import gulp and gulp-file-include. you will also create a variable paths to define the path of source and the destination path (where the static html files will be after the build) :
const gulp = require('gulp');
const fileinclude = require('gulp-file-include');
const paths = {
scripts: {
src: './',
dest: './build/'
}
};
In gulpfile.js file , create a task function that will be responsible for including html files and returning static files:
async function includeHTML(){
return gulp.src([
'*.html',
'!header.html', // ignore
'!footer.html' // ignore
])
.pipe(fileinclude({
prefix: '##',
basepath: '#file'
}))
.pipe(gulp.dest(paths.scripts.dest));
}
For now set function as default :
exports.default = includeHTML;
Add the include tags to index.html:
##include('./header.html')
<!-- Content -->
<section>
<h1>Hello world</h1>
</section>
##include('./footer.html')
Run the gulp command :
yarn gulp
The build folder will be created with index.html file inside
Done :)
Well, just as an ugly solution, try <iframe> tags. They load remote pages into your website, so you could define a "master template" like this:
...
<body>
<div id="content">
<iframe src="content1.html"></iframe>
...
Now, inside of content1.html, you could just write the content without the main layout.
Related
How can you use Gulp to gather in one html file a list of all the pages that are in the directory?
For example, in the build directory I have two files contact.html with title "Contacts" and faq.html with the title "Frequently asked questions", I need to get them and create a ui.html which would be a list of links to files of the form:
Frequently asked questions
Contacts
Well, with the addition of step your design (a connected css file).
Found the gulp-listing module, but it can not be customized, there it is as follows:
gulp.task('scripts', function() {
return gulp.src('./src/*.html')
.pipe(listing('listing.html'))
.pipe(gulp.dest('./src/'));
});
I used two gulp modules for do this.
gulp-filelist - for create file list
gulp-modify-file - for update this file
gulp
.src(['./html/**/*.html'])
.pipe(require('gulp-filelist')('filelist.js', { relative: true }))
.pipe(require('gulp-modify-file')((content) => {
const start = 'var list = '
return `${start}${content}`
}))
.pipe(gulp.dest('js'))
After run gulp, you got in js/filelist.js something like this:
var list = [
"Cancellation/template.html",
"Cancellation/email.html",
]
You can add this script in your html file, and with js display all info.
I'm making a simple proof-of-concept website using JSON as a data source and Handlebars for a templating engine, with a view to 'merging' the two things into a static HTML file.
The website will be very modular, so each component will be built using a distinct Handlebars 'partial', which will each consume data from its own JSON file.
The development structure I have so far is like this:
src/
models/
header.json
article.json
footer.json
partials/
header.hbs
article.hbs
footer.hbs
index.hbs
The contents of the index.hbs file is something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test App</title>
</head>
<body>
{{> header}}
{{> article}}
{{> footer}}
</body>
</html>
The partials are very simple for now. e.g header.hbs contains:
<header>{{header}}</header>
I have the following gulp file gulpfile.js which goes part way to what I want to achieve:
var gulp = require('gulp');
var data = require('gulp-data');
var handlebars = require('gulp-compile-handlebars');
var rename = require('gulp-rename');
gulp.task('default', function () {
var templateData = {
header: 'Welcome'
},
options = {
batch : ['./src/partials']
}
return gulp.src('src/index.hbs')
.pipe(handlebars(templateData, options))
.pipe(rename('index.html'))
.pipe(gulp.dest('dist'));
});
So far, it bundles in my partials together and outputs everything nicely, as HTML, in a file called dist/index.html.
The thing that's missing is the JSON data part. Currently the JSON data being consumed by the partials is defined in the gulp file (the variable templateData) but I want each partial to consume data from the src/models JSON files to provide clear separation. The name of the JSON file will be identical to the name of the .hbs partial it's consumed by.
I'm unclear how to go about this. The gulp-compile-handlebars documentation suggests that using gulp-data will support what I need, but I'm struggling to piece together anything from the gulp-data documentation that works for my specific use-case.
Could anyone please suggest how I could modify my gulp file to accomplish this?
Many thanks.
If I understand the question, you can use gulp-data to return an object from your models .json file and it will be added to your tempateData object.
Use gulp-data to pass a data object to the template based on the
handlebars file being processed. If you pass in template data this
will be extended with the object from gulp-data.
So this worked for me.
gulp.task('default', function () {
var templateData = {
header: 'Welcome'
},
options = {
batch : ['./src/partials']
}
return gulp.src('src/index.hbs')
.pipe(data(function(file) {
return require('./src/models/test.json');
}))
.pipe(handlebars(templateData, options))
.pipe(rename('index.html'))
.pipe(gulp.dest('dist'));
});
And you can modify the path to your .json file to match the name of the src .hbs file.
I'm working on an AngularJs/MVC app with Web API etc. which is using a CDN. I have managed to whitelist two URLs for Angular to use, a local CDN and a live CDN (web app hosted in Azure).
I can successfully ng-include a template from my local CDN domain, but the problem arises when I push the site to a UAT / Live environment, I cant be using a template on Localhost.
I need a way to be able to dynamically get the base url for the templates. The location on the server will always be the same, eg: rooturl/html/templates. I just need to be able to change the rooturl depending on the environment.
I was thinking if there was some way to store a global variable, possibly on the $rootScope somewhere that I can get to when using the templates and then set that to the url via Web API which will get return a config setting.
For example on my dev machine the var could be http://Localhost:52920/ but on my uat server it could be https://uat-cdn.com/
Any help would be greatly appreciated as I don't want to store Js, css, fonts etc on the CDN but not the HTML as it feels nasty.
Thanks I'm advance!
I think it's good practice to keep environment and global config stuff outside of Angular altogether, so it's not part of the normal build process and is harder to accidentally blow away during a deploy. One way is to include a script file containing just a single global variable:
var config = {
myBaseUrl: '/templates/',
otherStuff: 'whatever'
}
...and expose it to Angular via a service:
angular.module('myApp')
.factory('config', function () {
var config = window.config ? window.config : {}; // (or throw an error if it's not found)
// set defaults here if useful
config.myBaseUrl = config.myBaseUrl || 'defaultBaseUrlValue';
// etc
return config;
}
...so it's now injectable as a dependency anywhere you need it:
.controller('fooController', function (config, $scope), {
$scope.myBaseUrl = config.myBaseUrl;
}
Functionally speaking, this is not terribly different from dumping a global variable into $rootScope but I feel like it's a cleaner separation of app from environment.
If you decide to create a factory then it would look like this:
angular.module('myModule', [])
.factory('baseUrl', ['$location', function ($location) {
return {
getBaseUrl: function () {
return $location.hostname;
}
};
}]);
A provider could be handy if you want to make any type of customization during config.
Maybe you want to build the baseurl manually instead of using hostname property.
If you want to use it on the templates then you need to create a filter that reuses it:
angular.module('myModule').filter('anchorBuilder', ['baseUrl', function (baseUrl) {
return function (path) {
return baseUrl.getBaseUrl() + path;
}
}]);
And on the template:
EDIT
The above example was to create links but if you want to use it on a ng-include directive then you will have a function on your controller that uses the factory and returns the url.
// Template
<div ng-include src="urlBuilder('path')"></div>
//Controller
$scope.urlBuilder = function (path) {
return BaseUrl.getBaseUrl() + path;
};
Make sure to inject the factory in the controller
Background
I have a piece of LESS code that needs to be compiled at runtime with Less.js -- it calculates some things via JavaScript -- so I can't use the task runner, etc.
In my index.html, I have:
<head>
...
<link rel="stylesheet/less" href="assets/less/DynamicHeight.less" />
...
<script type="text/javascript" src="lib/less/less.js"></script>
...
</head>
Problem
Less.js appears unable to find the file:
And when I try to access the file directly, I see:
Question
How can I add the configuration that will allow this less file to be downloaded? Am I still able to use web.config files with vNext, or do I need to do something with config.json instead?
Lead 1: Should I use Owin?
Thinking this might be the right path but I'm pretty unfamiliar.
I see a number of tutorials out there, such as K. Scott Allen's, which reference code such as:
public void Configuration(IAppBuilder app)
{
var options = new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider()
};
((FileExtensionContentTypeProvider)options.ContentTypeProvider).Mappings.Add(
new KeyValuePair<string, string>(".less", "text/css"));
app.UseStaticFiles(options);
}
However, it appears that in its current version, asp.net is looking for a signature of Configure(IApplicationBuilder app) instead.
The IApplicationBuilder class doesn't have a method along the lines of UseStaticFiles -- it only has a signature of IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware).
I have a feeling that this is likely the right path to solve the issue -- I just can't find out how to propertly configure the IAppliationBuilder to map the MIME extension.
Okay, I believe I figured it out.
Step 1: Add the appropriate library for static files
In ASP.NET vNext, this is Microsoft.Aspnet.StaticFiles.
In your project.json file, add the following under "dependencies":
"Microsoft.AspNet.StaticFiles": "1.0.0-beta2"
This adds the static middleware method that you can use later.
Step 2: Configure the app to use Static Files
Add the using statement at the top:
using Microsoft.AspNet.StaticFiles;
At this point, the app.UseStaticFiles method will be available, so your Configure method can look as follows:
public void Configure(IApplicationBuilder app)
{
var options = new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider()
};
((FileExtensionContentTypeProvider)options.ContentTypeProvider).Mappings.Add(
new KeyValuePair<string, string>(".less", "text/css"));
app.UseStaticFiles(options);
}
And voila! I get text when browsing to .less files, and no more error is appearing from LessJS.
In .NET Core 1.0.1, SeanKileen answer is still good. The following is a simple code rewrite:
public void Configure(IApplicationBuilder app, ...)
var contentTypeProvider = new FileExtensionContentTypeProvider();
contentTypeProvider.Mappings[".map"] = "application/javascript";
contentTypeProvider.Mappings[".less"] = "text/css";
app.UseStaticFiles(new StaticFileOptions()
{
ContentTypeProvider = contentTypeProvider
});
The above code EXTENDS the default mapping list (see the source), which already has ~370 mappings.
Avoid using the FileExtensionContentTypeProvider constructor overload that takes a dictionary (as suggested by JHo) if you want those 370 default mappings.
SeanKilleen's answer is right on, and still works ASP.NET Core RC1. My only improvement is to write the exact same code using collection initializers to make it cleaner.
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
{
{ ".less", "text/css" },
{ ".babylon", "text/json" },
// ....
})
});
In a php file I can do:
<p><?php echo "hello!";?></p>
Is there a way to do this in node, if yes what's the logic for it?
I have an idea how could this be done:
Use an identifier markup for node in the HTML file like: <node>code</node>
Load & Parse HTML file in Node
Grab node markup from the HTML file and run it
But I'm not sure if this is the best way or even if it works :)
Please note I want to learn node.js, so express and other libraries and modules are not answers for me, because I want to know the logic of the process.
What your describing / asking for a node.js preprocessor. It does exist but it's considered harmful.
A better solution would be to use views used in express. Take a look at the screencasts.
If you must do everything from scratch then you can write a micro templating engine.
function render(_view, data) {
var view = render.views[view];
for (var key in data) {
var value = data[key];
view.replace("{{" + key + "}}", value);
}
return view;
}
render.views = {
"someView": "<p>{{foo}}</p>"
};
http.createServer(function(req, res) {
res.end(render("someView", {
"foo": "bar"
}));
});
There are good reasons why mixing php/asp/js code directly with HTML is bad. It does not promote seperation of concerns and leads to spaghetti code. The standard method these days is templating engines like the one above.
Want to learn more about micro templating? Read the article by J. Resig.
You can try using JooDee, a node webserver which allows you to embed serverside javascript in your web pages. If you are familiar with Node and PHP/ASP, it is a breeze to create pages. Here's a sample of what a page looks like below:
<!DOCTYPE html>
<html>
<: //server side code in here
var os = require('os');
var hostname = os.hostname();
:>
<body>
<div>Your hostname is <::hostname:></div>
</body>
</html>
Using JooDee also lets you expose server javascript vars to the client with no effort by attaching attributes to the 'Client' object server side, and accessing the generated 'Client' object in your client side javascript.
https://github.com/BigIroh/JooDee
Use a template engine. From terminal
npm install ejs
In code:
var ejs = require('ejs');
var options = {
locals: {
foo: function() { return "bar"; }
}
};
var template = "<p><%= foo() %></p>";
console.log(ejs.render(template, options));