How to make cross page reference work in Hugo? - hugo

I have a hugo project setup based on this theme and have the below project structure.
content
learning
aws
index.md
how-we-use
index.md
Inside the aws > index.md file, I want to have a link which opens up how-we-use > index.md. I tried below (and a lot other things), but every time I click it, it give me 404.
Tried below in aws > index.md.
- [How we use AWS](./how-we-use)
- [How we use AWS](/how-we-use)
- [How we use AWS](/learning/aws/how-we-use)
Below is my how-we-use > index.md
+++
title = "How we use AWS"
aliases = "/learning/aws/how-we-use/"
+++
Hi There
Also, tried changing this alias to /how-we-use/ and /how-we-use but still doesn't work.
config.toml
baseurl = "https://welcome-page"
title = "welcome"
theme = "hugo-universal-theme"
themesDir = "./themes"
languageCode = "en-us"
uglyURLs = false
# Site language. Available translations in the theme's `/i18n` directory.
defaultContentLanguage = "en"
# Define the number of posts per page
paginate = 10
# not pluralize title pages by default
pluralizelisttitles = false
[[menu.main]]
name = "Learnings"
identifier = "menu.learnings"
url = "/img/learnings.png"
weight = 4
[[menu.main]]
name = "Learnings"
identifier = "section.learnings"
url = ""
weight = 1
parent = "menu.learnings"
post = 1
[[menu.main]]
name = "AWS"
identifier = "learning.aws"
url = "/aws"
weight = 1
parent = "section.learnings"
How to get this cross reference to work ?
p.s - if I change the name of the files to _index.md, then no content is displayed and I just see the title getting displayed but nothing else.

md link format []() could be used with full link [](https://...) or with anchor [](#anchor), but you need relative link and hugo has another syntax for it: []({{< ref "" >}})
According to Hugo documentation index.md can be reference either by its path or by its containing folder without the ending /. _index.md can be referenced only by its containing folder.
So try it:
[How we use AWS]({{< ref "/how-we-use" >}})
It works with my ananke theme. But you could try also:
[How we use AWS]({{< ref "/how-we-use/index" >}})
[How we use AWS]({{< ref "/learning/aws/how-we-use" >}})
[How we use AWS]({{< ref "/learning/aws/how-we-use/index" >}})

Related

How do I embed code through my text editor?

I'm running Hugo and editing my pages using Notepad++. I'd like to embed some code similar to the page here.
My Hugo version is
Hugo Static Site Generator v0.55.6-A5D4C82D windows/amd64 BuildDate: 2019-05-18T07:57:00Z
My config.toml file is below. As you can see, I've added the pygments options to the top of the page:
pygmentsCodefences = true
pygmentsStyle = "autumn"
baseurl = "https://blakeshurtz.netlify.com/"
title = "Blake Shurtz"
theme = "hugo-creative-portfolio-theme"
languageCode = "en-us"
# Enable comments by entering your Disqus shortname
disqusShortname = ""
# Enable Google Analytics by entering your tracking code
googleAnalytics = ""
[params]
# Style options: default (pink), blue, green, pink, red, sea, violet
# Use custom.css for your custom styling
style = "default"
description = "Describe your website"
copyright = "©2019 Blake Shurtz"
sidebarAbout = [
"I am a research statistician who enjoys building models and apps.",
"Originally from the Bay Area, currently based in central CA."
]
# Contact page
# Since this template is static, the contact form uses www.formspree.io as a
# proxy. The form makes a POST request to their servers to send the actual
# email. Visitors can send up to a 1000 emails each month for free.
#
# What you need to do for the setup?
#
# - set your email address under 'email' below
# - upload the generated site to your server
# - send a dummy email yourself to confirm your account
# - click the confirm link in the email from www.formspree.io
# - you're done. Happy mailing!
email = "you#yoursite.com"
# Optional Matomo analytics (formerly piwik)
# [params.analytics.matomo]
# URL = "https://stats.example.com"
# ID = "42"
# # Track all subdomains with "*.example.com" (Optional)
# domain = "www.example.com"
# # Optional integrity check hash
# hash = ""
# Nav links in the side bar
[[params.navlinks]]
name = "Home"
url = "portfolio/"
home = true
[[params.navlinks]]
name = "About"
url = "about/"
[[params.navlinks]]
name = "Get in touch"
url = "contact/"
[params.social]
stackoverflow = "https://stats.stackexchange.com/users/206673/blake-shurtz"
twitter = "https://twitter.com/blakeobeans"
email = "blakeobeans#gmail.com"
linkedin = "https://www.linkedin.com/in/blakeshurtz/"
github = "https://github.com/blakeobeans"
Can someone give me an example of what I need to write in my text editor in order to include the code?
Thanks!
I'm assuming you mean using markdown syntax to format text as code.
Surround your code with three backticks at the beginning and at the end.
```python (or whatever language)
code here
```
As Ambrose Leung's answer mentions, you can include code blocks in markdown by wrapping them in 3 backticks:
```language
some code here
```
To get syntax highlighting, you can use Chroma, which is built into Hugo. Just add these lines to the top of your config.toml file (don't let the names confuse you, they say pygments but are for chroma):
pygmentsCodefences = true
pygmentsStyle = "pygments"
You can set the pygmentsStyle value to any of the styles from the style gallery.

Requiring all page objects within a directory recursively for Protractor Specs

Suppose I've ordered my page objects files in the following folders:
pages
modals
modal-1.coffee
modal-2.coffee
panels
panel-1.coffee
panel-2.coffee
subpanels
subpanel-1.coffee
subpanel-2.coffee
mainPage.coffee
As of right now, I'm requiring each page object individually at the top of my spec files like thus:
{Modal1} = require <path to modal-1>
...
{MainPage} = require <path to mainPage>
However, I'd like to be able to just make one call, along the lines of:
Pages = require <path to pages dir>
I found this SA question and this blog post. But I'm getting an error where while the page objects are being read (confirmed with console.log statements in my index.coffee file), their member functions are inaccessible:
Pages.MainPage is not a function
Cannot read property 'getSomething' of undefined
So my question is - how do I access the member functions of the page objects when I've exported them as a single module Pages?
Any insights would be really appreciated!
I am not familiar with coffeescript, but in JS you can try to re-export with
index.js
pages
modals
modal-1.coffee
modal-2.coffee
panels
panel-1.coffee
panel-2.coffee
subpanels
subpanel-1.coffee
subpanel-2.coffee
mainPage.coffee
index.coffee (?)
in your index file:
module.exports.modal-1 = require('modals/modal-1.coffee')
module.exports.modal-2 = require('modals/modal-2.coffee')
module.exports.panel-1 = require('panels/panel-1.coffee')
module.exports.mainPage = require('./mainPage.coffee')
// and so on
So in specs it would be -
let {modal-1, modal-2, mainPage} = require('pages')
https://nodejs.org/api/modules.html#modules_folders_as_modules
If there is no package.json file present in the directory, then
Node.js will attempt to load an index.js

How to use template parameters in page content in hugo

Is it possible to use template parameters in the content of a post with Hugo? E.g. if I have the following parameters:
[params.company]
name = "My Company"
Can I then do something like this in the content of a post?
This site, {{ .Site.BaseURL }} is operated by {{ params.company.name }}
I've tried, but it's literally printing the above instead of interpolating the variables.
1. Front matter way
As far as I'm aware, it's not possible* to put variables within the markdown file's content because MD parser would strip them, but it's possible to do it using custom variables on the front matter of each .md content file. The Hugo engine can target any fields you set in front matter. Front matter fields can be unique as well.
In your case, the template which is called to show the rendered .MD file has access to front matter parameters and you can change template's behaviour (like add classes of extra <div>'s) or even pull the content right from the parameter.
For example, on my .md files I have:
---
title: "Post about the front matter"
<more key pairs>
nointro: false
---
The key nointro: true would make my first paragraph to be normal size. Otherwise, if key is absent or false, first paragraph would be shown at larger font size. Technically, it's adding a custom class on a <div>.
In the template, I tap into the custom parameter nointro this way:
parent template which shows your markdown file, which has front matter parameters:
<div class="article-body {{ if .Params.nointro }} no_intro {{ end }}">
{{ .Content }}
</div><!-- .article-body -->
Notice I can't put variables within {{ .Content }}, but I can outside of it.
For posterity, that's piece of the content from a file hugo/themes/highlighter/layouts/partials/blog-single-content.html, it's a partial for single post content. You can arrange your partials any way you like.
Obviously, that's Boolean parameter flag, but equally it could be content which you could use directly:
MD file's top:
---
title: "One of our clients"
<more key pairs>
companyname: "Code and Send Ltd"
---
Text content is put here.
Then, reference it like this (extra insurance against blank value using IF):
Anywhere in Hugo template files:
{{ if .Params.companyname }}{{ .Params.companyname }}{{ end }}
2. Using config.(toml/yaml/json)
Now, looking at your example, "This site is operated by " would almost warrant a custom field in more global location, for example, hugo/config.toml. If I wanted to add a companyname into my config, I'd do it this way:
hugo/config.toml:
BaseURL = "_%%WWWPATH%%_"
languageCode = "en-uk"
title = "Code and Send"
pygmentsUseClasses = true
author = "Roy Reveltas"
theme = "Highlighter"
[params]
companyname = ""
Then I'd use it anywhere via {{ .Site.Params.headercommentblock }}.
I guess if you want your client pages to be static pages then single location might not be the best and you might want to tap into front-matter. Otherwise, if it's a site's footer, this way is better. Alternatively, you could even put this data even on data files.
3. Using custom placeholders and replacing via Gulp/npm scripts
I said not possible*, but it's possible, although unconventional and more risky.
I had such setup when I needed two builds for my website: 1) Prod and 2) Dev. Prod URL's were coming from two places: CDN and my server. Dev had to come from a single place in a static folder because I wanted to see images and was often working offline on a train.
To solve that, I used two custom variables in all my templates (including markdown content): _%%WWWPATH%%_ and _%%CDNPATH%%_. I came up with this unique pattern myself by the way, feel free to adapt it. Then, I put it also on hugo/config.toml as:
hugo/config.toml:
BaseURL = "_%%WWWPATH%%_"
After Hugo happily generated the website with those placeholders, I finished off the HTML's using a Grunt task:
grunt file:
replace: {
dev: {
options: {
patterns: [{
match: /_%%CDNPATH%%_+/g,
replacement: function () {
return 'http://127.0.0.1:1313/'
}
}, {
match: /_%%WWWPATH%%_+/g,
replacement: function () {
return 'http://127.0.0.1:1313/'
}
}...
For posterity, I recommend Gulp and/or npm scripts, I'd avoid Grunt. This is my older code example above from the days when Grunt was the best.
If you go this route, it's riskier than Hugo params because Hugo won't error-out when your placeholder values are missing or anything else wrong happens and placeholders might spill into the production code.
Going this route you should add multiple layers of catch-nets, ranging from simple following Gulp/Grunt/npm scripts step which searches for your placeholder pattern to pre-commit hooks ran via Husky on npm scripts that prevent from committing any code that has certain patterns (for example, %%_). For example, at a very basic level, you would instruct Husky to search for anything before allowing committing this way:
package.json of your repo:
"scripts": {
"no-spilled-placeholders": "echo \"\n\\033[0;93m* Checking for spilled placeholders:\\033[0m\"; grep -q -r \"%%_\" dist/ && echo \"Placeholders found! Stopping.\n\" && exit 1 || echo \"All OK.\n\"",
"precommit": "npm run no-spilled-placeholders"
},
Basically, grep for pattern %%_ and exit with error code if found. Don't forget to escape the code because it's JSON. I use similar (more advanced) setup in production and nothing slips through. In proper setup you should creatively look for anything mis-typed, including: %_, _%, %__, __% and so on.
Normal Go template is not supported in the markdown file, but shortcodes are:
{{< param "company.name" >}}
To access arbitrary other Go template values, create a custom shortcode for it and call that from your markdown file.
For your example, you need the site's baseUrl, so save this as layouts/shortcodes/base_url.html:
{{ .Site.BaseURL }}
And write this in your markdown file:
+++
[company]
name = "My Company"
+++
This site, {{< base_url >}} is operated by {{< param "company.name" >}}
There is also the shortcode param : {{< param "companyName" >}} : https://gohugo.io/content-management/shortcodes/#param

How to get node path from id on multi lingual website?

I have a node, with nid. i.e. 78 and it's on French language (main language is English) so local name to it is:
fr/node/78
or just
node/78
?
Also that page has some alias, i.e. "hello" so it's relative path would be:
/fr/hello
How can I get that relative path?
Yes, I know that:
$alias = drupal_get_path_alias('node/78');
should give me my page alias, but it's not working, probably because of different language?!? Or that should be:
$alias = drupal_get_path_alias('fr/node/78');
I tried both, but none of them is working?!? I can't believe that there is no simple function available, which would take node id as parameter and return SEO (with alias) page path?!?
Please help. What is the easiest way to get node seo path on multi lingual website if I have nid?
Finally I got it. In case somebody else strugles with this:
// Returns root relative path
function get_node_url_ml ($nid, $language){
$defaultLanguage = language_default();
$local_path = 'node/' . $nid;
$url = drupal_lookup_path('alias', $local_path, $language);
if (!$url) $url = 'node/' . $nid;
if ($language != $defaultLanguage->language) $url = $language.'/'.$url;
return '/'.$url;
}

"=" symbols in GAE TextProperty

I'm getting strange additional symbols (=) in text property when adding text there via POST.
For example:
The team is back with an unstoppable fury as they are being chased by the p= olice, Alonzo and Yuuma. Vinnie, Shorty and Kiro=92s skills will be put to = the test.
There shouldn't be any of = symbols in that text.
My co de is:
class FileUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
game_file = self.get_uploads()[1]
screen_file = self.get_uploads()[0]
if not users.get_current_user():
game_file.delete()
screen_file.delete()
self.redirect(users.create_login_url("/"))
return
game = Game()
game.title = self.request.get('title')
game.url_name = self.request.get('url')
if self.request.get('active') == 'active':
game.active = True
else:
game.active = False
if self.request.get('featured') == 'featured':
game.featured = True
else:
game.featured = False
query = Category.gql("WHERE url_name = :url_name", url_name=self.request.get('category'))
game.category = query.get()
game.width = int(self.request.get('width'))
game.height = int(self.request.get('height'))
game.description = db.Text(self.request.get('desc'))
game.how_to_play = db.Text(self.request.get('htp'))
game.game_file = game_file
game.game_screenshot = screen_file
db.put(game)
What am i doing wrong?
This is a known issue of blobstore handler that is breaking the data encoding.
I had the same difficulty. But, I found a fix. I'm using Python 2.5. In my model, I have a TextProperty, hooked up to an html TextArea tag. Like your situation, in the Dev server, it saved what I entered. However, in Prod, the DataStore somehow added "= " among others, every time I write the content of textarea over to the textproperty field.
Go here:
http://code.google.com/p/googleappengine/issues/detail?id=2749
Then, scroll down to Comment 21. The poster of that comment attached a file, named appengine_config.py Download it, and put it on the root folder of your app. Then Deploy it to Prod and try it out in Prod.
I did that, and my "= " problem went away.

Resources