How do I embed code through my text editor? - hugo

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.

Related

How to make cross page reference work in 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" >}})

Programatically add a page to a known parent

I would like to create programatically a sub page for a known parent. How can I do that? The page creation will takes place in a signal receiver: the page is created on publication of another page.
Add a revision as well.
from wagtail.wagtailcore.models import Page
from models import MyPage
home = Page.objects.get(id=3) # or better Page query
my_page = MyPage(title="test", body="<h1>the body</h1>")
home.add_child(instance=my_page)
# later when a cms user updates the page manually
# there will be no first revision to compare against unless
# you add a page revision also programmatically.
my_page.save_revision().publish()
You can see how wagtail does this in the wagtailadmin pages create view (line 156).
https://github.com/wagtail/wagtail/blob/stable/1.13.x/wagtail/wagtailadmin/views/pages.py
Update 2018-09-18:
I built a 700 page site including 200 generated pages. I never added an initial Revision anywhere and no editors complained. After the first manual edit there will be a Revision. Go ahead and add an initial Revision if you think it is needed for traceability.
To create a page programmatically:
page = SomePageType(title="My new page", body="<p>Hello world</p>") # adjust fields to match your page type
parent_page.add_child(instance=page)
Below is my complete code to create a multi language page structure programatically. It will replace the "Wagtail Welcome Page" with a LanguageRedirectionPage instance.
More information about multi language pages:
Wagtail Docs - Internationalization
The page structure is as follows:
Page
LanguageRedirectionPage (will redirect to /en)
Page (en)
Page (de)
Page (fr)
where the created Site instance at the end of the code points to the LanguageRedirectionPage instance. This is the entry point of our application.
# Deletes existing pages and sites
Site.objects.all().delete()
Page.objects.filter(pk=2).delete() # Deletes Wagtail welcome page
root_page = Page.objects.filter(pk=1).get()
# Adds a LanguageRedirectionPage as a child of the Root Page
app_name = '[Your Project Name]'
page_slug = app_name.lower().replace(" ", "")
sub_root_page = LanguageRedirectionPage(
title=app_name,
draft_title=app_name,
slug=page_slug,
live=True,
owner=account,
)
root_page.add_child(instance=sub_root_page)
sub_root_page.save_revision().publish()
# Adds some language pages
for code,caption in dict(settings.LANGUAGES).items():
print(code, caption)
sub_root_page.add_child(instance=Page(
title=caption,
slug=code,
live=True,
owner=account,
))
# Adds a new Site instance (See Settings -> Sites in your Wagtail admin panel)
Site.objects.create(
hostname='localhost',
port='80',
site_name=app_name,
root_page=sub_root_page,
is_default_site=True,
)

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 can I get the thumbnail that nautilus uses for a given file?

Nautilus shows me a thumbnail of a file, if its an image it will show me a preview, if its a video it will show a frame from the video, if its a document it will show me the application icon.
How can I access the image?
I see they are cached in ~/.thumbnail/ however they are all given unique names.
the thumbnail filename is an md5 of the filename. However the filename
is the absolute URI to the image (without a newline).
So you need to do:
echo -n 'file:///home/yuzem/pics/foo.jpg' | md5sum
And if it has spaces, you need to convert them to '%20', ex for "foo bar.jpg"
echo -n 'file:///home/yuzem/pics/foo%20bar.jpg' | md5sum
Found at Ubuntu forums. See also the Thumbnail Managing Standard document, linked from the freedesktop.org wiki.
Simple Python tool to calculate the thumbnail path. Written by Raja, shared as an ActiveState code recipe. Note, however, that this code does not escape filenames with spaces or special characters; which means this code does not work for all filenames.
"""Get the thumbnail stored on the system.
Should work on any linux system following the desktop standards"""
import hashlib
import os
def get_thumbnailfile(filename):
"""Given the filename for an image, return the path to the thumbnail file.
Returns None if there is no thumbnail file.
"""
# Generate the md5 hash of the file uri
file_hash = hashlib.md5('file://'+filename).hexdigest()
# the thumbnail file is stored in the ~/.thumbnails/normal folder
# it is a png file and name is the md5 hash calculated earlier
tb_filename = os.path.join(os.path.expanduser('~/.thumbnails/normal'),
file_hash) + '.png'
if os.path.exists(tb_filename):
return tb_filename
else:
return None
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
print('Usage: get_thumbnail.py filename')
sys.exit(0)
filename = sys.argv[1]
tb_filename = get_thumbnailfile(filename)
if tb_filename:
print('Thumbnail for file %s is located at %s' %(filename, tb_filename))
else:
print('No thumbnail found')
I guess that you need to access the thumbnail programatically. You want to use the Gio library.
I haven't been able to find a way to check for the thumbnail and, if it doesn't exist, go for the application icon, so you need to do it in two steps. Here you have a sample (sorry, Python. I'm not fluent in C):
import gio
import gtk
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.show()
hbox = gtk.HBox()
hbox.show()
window.add(hbox)
f = gio.File(path='/home/whatever/you/want.jpg')
info = f.query_info('*')
# We check if there's a thumbnail for our file
preview = info.get_attribute_byte_string ("thumbnail::path")
image = None
if preview:
image = gtk.image_new_from_file (preview)
else:
# If there's no thumbnail, we check get_icon, who checks the
# file's mimetype, and returns the correct stock icon.
icon = info.get_icon()
image = gtk.image_new_from_gicon (icon, gtk.ICON_SIZE_MENU)
hbox.add (image)
window.show_all()
gtk.main()

"=" 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