how to access Hugo's template variables in a javascript file? - hugo

I'm trying to use react.js in Hugo. I know Go template variables are accessible in HTML file.
My question is how to access them in javascript. or is there a workaround?
thanks in advance.
UPDATE:
currently my workaround is to use meta tags in HTML and load Go template variables like this:
<meta name="title" content={{.Title}} />
and then in javascript,
function getMetaTitle() {
var metas = document.getElementsByTagName('meta');
for (i=0; i<metas.length; i++) {
if (metas[i].getAttribute("name") == "title") {
return metas[i].getAttribute("content");
}
}
return "failed to access...";
}
var metaTitle = getMetaTitle();
but this way is inconvenient when the number of meta tags growing, is there a more concise way to do this?

I doubt Hugo and React is a good pair but that's off topic and I might be wrong about that. You are asking, how to get Hugo variables into website's JavaScript. My answer:
Hugo is static website engine, so it only converts templates and markup documents (with your content) into HTML files. Now, when you upload your files onto your server, your JS cannot see anything Hugo — only your files.
The question becomes, how to transfer Hugo variables into some files of your website.
As you suggested, it's best to write variables into your HTML (or JSON) using Hugo, then read them by JS. If it's small amount, use attributes or tags. If there's a lot and it doesn't differ per-page, use a separate JSON file.
For example, personally I have a multilingual site which a) requires different language titles to appear dynamically via JS; b) uses JS which queries different Lunr.js search indexes in JSON format.
For both I use data-<name> attributes:
<section class="section-search" data-index="{{ .Site.BaseURL }}searchIndex.json" id="section-search">
<input type="search" id="search-input" placeholder="{{ ( index $.Site.Data.translations $.Site.Params.locale ).dataloading }}" data-loaded="{{ ( index $.Site.Data.translations $.Site.Params.locale ).dataloaded }}">
<!-- search button goes here -->
</section>
For example, on English templates (rendered into /public/), data-loaded attribute would be in English, but for Lithuanian templates (rendered into /public/lt/), data-loaded attribute would be in Lithuanian.
I wouldn't worry about "growing meta tags", but you could maybe write variables into a JSON file and then read it in JS if you are concerned about HTML bloat?
I'm building custom JSON first as HTML, then minifying/renaming it into JSON when building indexes for Hugo Lunr search as per this recipe. Instead of "baking in" the content with range as in mentioned recipe, you could simply list all the variables.
By the way, I'm using npm scripts as a build runner (instead of Grunt/Gulp) so I use json-minify:
"index:prepare": "json-minify public/json/index.html > public/site-index.json",
You could "bake" JSON files with any content (including Hugo template variables) via Hugo this way. Hope it helps.

You can specify a custom output format for Javascript within your config.toml so that Hugo then treats those particular formats and file extensions like it's content files where it replaces the template variables with adequate values.
So, an entry such as below in your config.toml will treat javascript files as one of the media type it needs to consider for its custom output formats:
[mediaTypes]
[mediaTypes."application/javascript"]
suffix = "js"
You can read more about it here

You can, of course, inline your JS in your layout files, but that is probably not what you want.
There have been some discussions about improvements in this area on the Hugo discussion site, but nothing concrete yet.

Related

How do I use JSON as a source of content in a 2sxc app?

I have a JSON file that has some simple fields and content. I want to make a 2sxc app that simply lists out the content of the JSON file using C# Razor. (Ultimately this json file will be hosted elsewhere).
Ideally, the content will be rendered as simple HTML in the page that I can see when I click view source in the browser so I know it's SEO friendly.
Is this possible? What kind of code would I need to do this?
I was able to figure it out using this example: https://2sxc.org/dnn-tutorials/en/razor/json/home
So my code looked something like this:
#inherits ToSic.Sxc.Dnn.RazorComponent
#inherits Custom.Hybrid.Razor12
#{
var someJson = System.IO.File.ReadAllText(App.PhysicalPath + "/json/UseCases.json");
var thing = AsDynamic(someJson);
}
#foreach(var useCase in thing.UseCases) {
#useCase.URLPart
<h3>Name: #useCase.Name</h3>
<h4>#useCase.Domain</h4>
<p>#useCase.ShortDescription</p>
#Html.Raw(useCase.Highlights)
}

With Hugo, can we use HTML code in a md file?

With Hugo, I am writing some HTML5 as Goldmark markdown doesn't support CSS classes or IDs.
My code is in post1.md :
<h2 data-toggle="collapse" data-target="#collapse-definition" aria-expanded="false" aria-controls="collapse-definition">Définition</h2> is not compiled and is not compiled to HTML.
Even the simplest div markup is omitted.
Thanks for your help.
From version 0.6, Hugo uses Goldmark for markdown.
For security reasons, Goldmark wipes HTML code.
However, if you use HTML frequently in your site, you can add to your config.toml
[markup.goldmark.renderer]
unsafe = true # Allow HTML in md files
For a less frequent usage of HTML, you can add safeHTML parameter to your HTML string (Hugo doc for safeHTML).

Gatsby Use plain html with frontmatter as source

I am migrating from a handlebars based static site generator. Authors of pages are allowed to use either html or markdown. Therefore i have lots of partial html files for which i need to create pages. These html files are in fact .hbs file (handlebars), but there are no expressions, just plain html element with some frontmatter.
For example:
---
title: Example
author: Narendra
---
<div>
<h1>Example</h1>
<p> .. </p>
</div>
Authors are able to drop these files inside a directory structure.
I have not been able to find a transformer that can deal with such file. Am i missing something? Do i need to create a custom transformer for this.
AFAIK markdown is a superset of html, so gatsby-transformer-remark should be able to handle these .hbs.
Unfortunately there's no way that I know to make gatsby remark accept .hbs extension, but I think renaming them should do the trick.

Show multiple pages of PDF with Angular and pdf.js

I want to show PDFs in my angular application. It should be possible to show multiple pages at once and to search inside the PDF.
I tried angularjs-pdf to do so, but it lacks these features. Is there a angular wrapper for pdf.js that can do this? Or can somebody get me startet on how to implement pdf.js in my angular application without a wrapper?
Assuming this statement:
"I want to show PDFs in my angular application"
Anyone searching for this, could ought to check out ng2-pdf-viewer, for more information on this module, can check this out ng2-pdf-viewer PdfShowcase
Basically, this module could somewhat allow one to display more than one PDF in a single screen.
app.component.ts
// Declare the pdf as an empty array
pdfs = [];
// Assuming requesting PDFs from server through MVC style
getPdfs(){
this.getPdfService.getPdfs().subscribe(response => {
response.body.forEach((value, index) => {
this.pdfs.push({
id: index,
obj: window.URL.createObjectURL(value);
});
});
});
}
app.component.html
<div *ngFor="let pdf of pdfs, index as i;">
<div *ngIf="pdf[i]">
<pdf-viewer
[rotation]="0"
[original-size]="true"
[show-all]="true"
[fit-to-page]="true"
[zoom]="0"
[zoom-scale]="'page-width'"
[stick-to-page]="true"
[render-text]="false"
[external-link-target]="'blank'"
[autoresize]="true"
[show-borders]="true"
[src]="pdf.obj"
(after-load-complete)="onPdfComplete($event)"
(error)="onPdfError($event)"
style="width: 100%; height: 800px;">
</pdf-viewer>
</div>
</div>
If this library is not suitable for your use case, you may try with other libraries which uses iframe or similar strategy. Refer here is a useful source worth checking it out.
I know I'm a little bit late for this post but thought of posting here might help some folks who is looking for the same thing. Hope it helps.
From ng2-pdf viewer page, it recommends your desire "angular wrapper for pdf.js", There are a ton of built in functionality Mozilla's viewer supports; such as print, download, bookmark, fullscreen, open file, zoom, search,......
If you need to display multiple PDF files simultaneously and if you don't mind using iFrames, I recommend ng2-pdfjs-viewer. https://www.npmjs.com/package/ng2-pdfjs-viewer

How To Display HTML Tags Saved In Database Using Symfony 2 and Twig

I've managed to build a page that will display data from the database dynamically. However, this code which is saved in the database:
<p>This is the content for the radio page.</p>
Displays like this:
<p>This is the content for the radio page.</p>
The HTML tags aren't rendered. I understand that Symfony (for security purposes) renders any HTML code like this for security reasons. I want Symfony (obviously) to render these HTML tags. How can I achieve this just for this purpose only, so that Symfony still sanitises any HTML tag that is saved to the database elsewhere on the site?
For your information as well, this is the code that I am using to pull the data from the database:
public function mainpageAction($slug)
{
$content = $this->getDoctrine()
->getRepository('SiteMainBundle:Content')
->find($slug);
if (!$content) {
throw $this->createNotFoundException('No product found for slug '.$slug);
}
return $this->render('SiteMainBundle:Default:page.html.twig', array('content' => $content, 'slug' => $slug));
}
Also, just so I can learn more about Symfony, is the rendering of the HTML tags just the sole job of PHP or could it be rendered properly using Twig?
Many thanks!
If you want to do that, you need to use the raw filter in the twig template. Like described in the twig documentation, the raw filter marks the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped if raw is the last filter applied to it.
In your case, it's : {{ content | raw }}

Resources