I want add a css file in only index.html page using if with pug. I have got this code with pug:
- var thepage = { page: './index.html' }
if thepage.page
link(rel="stylesheet", type="text/css", href="../css/slider.min.css")
There are no errors with gulp but it doesn't work.
Try this code below.
It works with the parcel
- var page = location.pathname.split('/').pop();
if (page == '404.pug') {
link(rel="stylesheet", href="css/cli/index.css")
}
else if (page=='index.pug') {
link(rel="stylesheet", href="css/index.css")
}
else {
link(rel="stylesheet", href="css/style.css")
}
Normally pug doesn't get a copy of the request inside the template, it depends on you passing it in from the route. It's pretty easy to add the path though:
res.render('index', { "path": req.path });
Then you can test for the path in your template.
if path === '/'
link(rel="stylesheet", type="text/css", href="../css/slider.min.css")
Given that you only want this rendered in one page it's probably even easier to put a boolean in your res.render for that one page. This also has the added advantage of moving data/decision logic back into the route and leaving the pug template focused only on display logic (a very important factor in writing large pug apps).
res.render('index', { "includeSlider": true });
Then the template can look like this:
if includeSlider
link(rel="stylesheet", type="text/css", href="../css/slider.min.css")
Related
I have been converting a WordPress site to Gatsby, and everything works nicely with gatsby develop, however after building with gatsby build some pages seem to render with only the page body and no wrapper layout or styling. I am using markdown pages with mdx, and I have all my markdown files under subfolders of the src/pages directory, like this:
src/pages/
--project/
--contact.md
--outputs.md
--project.md
--sources.md
--software/
--apps.md
--frontend.md
--system.md
The above structure is more for organizational reasons than anything else (there are many more mdx files in reality). It does also correspond to the overall path structure of the site, however. In my built site, when I go to http://localhost:9000/contact the page renders perfectly, but when I visit http://localhost:9000/project or any other pages relating to that folder I only see the page body (the text content), with no layout component wrapper or styling. Everything under the software folder renders fine.
Each markdown file has a slug defined in the usual way in the frontmatter. The slug defined in src/project/project.md is just '/project'. The slug for src/project/contact.md is '/project/contact'.
Clearly the presence of src/pages/project/project.md is causing problems, but I can't figure out exactly why. I tried renaming that to src/pages/project/index.md, but that did nothing. Interestingly, when I look at public/project I see an index.html at the top level, with subfolders for each subpage, each containing its index.html. For public/software there is no index.html at the top level.
My gatsby-config.js (relevant parts):
{
resolve: `gatsby-source-filesystem`,
options: {
name: `pages`,
path: `${__dirname}/src/pages`,
},
},
{
resolve: `gatsby-plugin-mdx`,
options: {
extensions: [`.md`, `.mdx`, `.markdown`],
gatsbyRemarkPlugins: [
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 1024,
},
},
],
},
},
My template (under templates/page.js - I use some MUI components):
export default function SitePageTemplate({ data: { mdx } }) {
const { frontmatter, body } = mdx;
const { title } = frontmatter;
return (
<Layout>
<Seo title={title} />
<Container fixed>
<Stack direction="row" justifyContent="space-between">
<SideBar/>
<div style={ { padding: "0 0 0 3.5%", width: "75%" } }>
<MDXRenderer>{body}</MDXRenderer>
</div>
</Stack>
</Container>
</Layout>
);
}
export const pageQuery = graphql`
query ($id: String!) {
mdx(id: { eq: $id }) {
body
frontmatter {
date(formatString: "MMMM DD, YYYY")
slug
title
}
}
}`
My gatsby-node.js:
const path = require("path");
exports.createPages = async ({ graphql, actions, reporter }) => {
const { createPage } = actions
createPage({
path: "/using-dsg",
component: require.resolve("./src/templates/using-dsg.js"),
context: {},
defer: true,
})
const result = await graphql(`
query MARKDOWN {
allMdx {
edges {
node {
id
frontmatter {
date(formatString: "MMMM DD, YYYY")
slug
title
}
}
}
}
}
`);
if (result.errors) {
reporter.panicOnBuild("🚨 ERROR: Loading \"createPages\" query");
}
const md = result.data.allMdx.edges;
md.forEach(({ node }, index) => {
createPage({
// This component will wrap our MDX content
component: path.resolve("./src/templates/page.js"),
// Pass any value you want to access inside the template. They'll be available via `props`.
context: {
id: node.id
},
// Slug defined with frontmatter in each MDX file.
path: node.frontmatter.slug
});
});
}
If I place all the markdown files flat under the src/pages directory the problem goes away. But I would like to retain the above folder layout so that the markdown is organized properly. How can I do this whilst at the same time avoiding this problem?
OK, returning to this issue after a few months, I think I finally solved it. A warning I was also getting turned out to be the real clue - initially I had thought it unrelated to this issue. At develop and at build time I was getting a warning in the following format:
warn Non-deterministic routing danger: Attempting to create page: "/project/contact/", but page
"/project/contact" already exists
Others have reported this warning, but none of the reasons or propsed fixes seemed to relate to my problem. Looking at my gatsby-config.js, however, I noticed that I had at some time included the gatsby-plugin-page-creator plugin. I suspected that somehow this might be generating pages in addition to the mdx plugin. And it seemed as if this was right - removing the plugin removed both the warnings about duplicate page creation and also fixed my rendering problems. Everything looks fine now, for both development and production versions of my site.
I can't remember why I originally included this plugin - I was originally using the mdx extension for my markdown files, and I think I needed gatsby-plugin-page-creator so that files with that extension would be correctly interpreted as markdown. I now use the standard md extension, and removing gatsby-plugin-page-creator doesn't cause any problems.
On the html for my page I have a <script id="pagedata"></script> element which I would like to add an element to only if a certain partial is rendered. In my layout.cshtml I have the following:
#if (Brand != null)
{
#Html.Partial("_UseApp");
}
And in my _UseApp.cshtml:
#{
var iosAppUrl = // retrieve iosLink from our CRM database
var androidUrl = // retrieve android link from our CRM database
// Here I want to add the above variables to the <script id=pagedata> in the html page. Something
like this:
PageData.AddPageData("appstore", iosAppUrl);
PageData.AddPageData("playstore", androidUrl);
I cannot work out how to do this - I set breakpoints in the UseApp.cshtml file and the file is being called, but I don't know how to add these script elements. I don't want to just add them into the layout file because I want to keep the app logic separate. Can anyone help? Thanks
My approach to this would be to use jQuery, as reading HTML elements in C# is rather difficult.
In the script below, it checks if the HTML exists, and if it does, we will assign an attribute to it. The second argument in attr() will be your link, note that you can use C# to get the value from your Db, by using the model or ViewBag.
#section Scripts{
<script>
$(document).ready(function () { // on ready
if ($("#replaceWithYourId").length) { // check if ID exists
$("#pagedata").attr("data-playstore", "link") // use jQuery attr method.
}
});
</script>
}
I want to use an html page with common code for all the other html pages. I know how to do with with css but I tried and failed with html. The code I am using and changing constantly is present on all the other pages so it's annoying to continually go through each page to change it. How can I do this?
you can use this plain html + js alternative : https://www.w3schools.com/howto/howto_html_include.asp
with example : https://www.w3schools.com/howto/tryit.asp?filename=tryhow_html_include_2
See the example :
<!DOCTYPE html>
<html>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
</script>
<body>
<div w3-include-html="h1.html"></div>
<div w3-include-html="content.html"></div>
<script>
includeHTML();
</script>
</body>
</html>
you can use iframe to split the content of the page. for example if the header is always the same you can place it in a iframe so if you modify it, chenges will affect all the pages. but I think this method is obsolete.
you could convert your html pages into a php instead and split the static code in another php file so in all pages you could include the static content.
I am assuming you are just getting started. So here are high level the three options you have in order of what is most easy to implement (not necessarily what is technically the best):
Use iframes. These allow you to load one HTML page into another, so you can have an outer page that has the common content and the changing content goes into the iframe.
Use JavaScript, you could have a basic page and then load the other content using JavaScript. A very simple way is to use the jQuery library which has a load() function that could do what you need.
Generate the HTML dynamically on the server. There are a lot of different ways. The easiest would be PHP.
I'm writing a book using HTML. If I write it in one html file, the whole code becomes long, so I want to save each chapters to different files and load them in main html. I mean there are files like chapter1.html, chapter2.html, ... and I want to include the contents of them in the other file main.html.
Is this possible?
If you wish to do this dynamically. you can use javascript instead of <iframe>. Save the HTML content you want to include inside content.html
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("data-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("data-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
}
</script>
You can Add it to the HTML page Later like below.
<div data-include-html="content.html"></div>
You could use iframe to embed each page into main.html
For example:
<iframe src="chapter1.html"></iframe>
<iframe src="chapter2.html"></iframe>
You could also create it into a slideshow, so that it looks more like a book.
That depends on what you want to achieve. In general it's not bad to split the content by Chapters and just link to them. That way the reader isn't overwhelmed and if the book is large it reduces loading time.
Where and how do you want to publish that book? HTML provides multiple means to do what you want (Frames and iFrames, both not that "cool" nowadays), however if you're using some Server Side Scripting (like a CMS), you could use other means there.
Or you could have seperated html files and then use some simple concatenation (like with batch/linux shell) to generate a the big output html then.
I would like to perform web test and learning like some makes music by sampling. So, I would like to make a new design by compozing with them and add my touch.
Say I have the html, css, js, etc files from the site owner, I imagine it is possible to automatically build templates and layouts as HALM and LESS or SASS files from them. For example, a html parser may find nested common structures in pages. A css parser may find common constants and replace them by variables.
Does such tool already exists ? Or what could be the cavits to develop one ?
Exemple for CSS:
From:
h1 { background-color: #ff14a6; }
h2 { color: #ff14a6; }
To:
$primary: #ff14a6;
h1 { background-color: $primary; }
h2 { color: $primary; }
HTML is formed from: Layout + Template, where Layout is the overall structure of the HTML page. Here is a Ruby example:
File: layout.erb
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> ... etc.
</head>
<body>
<%= yield =>
</body>
</html>
Template replaces layout's yield.
Some layout content is page-specific, while template contains frontmatter. In template (contact.html.erb):
---
title: "Contact Information"
---
In layout (layout.erb):
<title> <%= current_page.data.title %>
</title>
If you want to create a template for whatever information you want to display your best bet is a JSON container to hold the new data and your javascript + jquery to import the data to the html. This could be done with a separate js file for the new data or the same one as the app/web page constructor js file.
This way you could have a set template layout for importing your data and then just change the file if you want to use different data. Alternatively using a framework like knockoutjs or something similar could allow you to do this as well, depending ofc on what you are familiar with or like to use.
The following snippet is a demo of jQuery using data from a JSON object to place data in the HTML (this would be the script.js file):
var view = {
displayStuff: function(obj){
var HTMLwelcomeMsg = '<span class="welcome-message">%data%</span>';
var formattedWelcome = HTMLwelcomeMsg.replace("%data%", obj.welcomeMessage);
$("#header").append(formattedWelcome);
}}
The JSON data can be in a separate file loaded by the JS or the HTML:
var model = {
"dataSample1" : "Some data",
"welcomeMessage" : "Welcome to the sample website",
"dataSample2" : "Some more data",
"someNumbers" : [1,1,253,669],
"moreVars" : {
"someMoreData" : ["123 31st st", "311 2nd st"],
"phoneNums" : ["555-5555", "999-999"]
}
}
Or you can put the data inside the JS file you use to append the elements to the HTML.
Then you call your view from the controller:
var controller = function(){
view.displayStuff(model);
}
and it all just works.