angular 4 json pipe - spaces not trimmed in pre tag - html

I have this json that I'm trying to pretty-print:
{
"error": "BAD_RESULT",
"status": 500,
"description": "Something bad happenned."
}
This object is stored in a variable errorMsg, and displayed in html using the pre tag like so:
<pre>
{{ errorMsg | json }}
</pre>
Unfortunately, when I inspect the element in the developers console, I see that the content inside the pre tag is padded with lots of spaces (right after the opening pre, and right before the closing pre), and that causes an indentation of the opening bracket. If I manually delete the spaces from the console, the json is displayed perfectly. How can it be solved? Is there a pure css solution or maybe with js?
Thanks.
EDIT:
My code was originally:
<pre>
{{ errorMsg | json }}
</pre>
When it was supposed to be:
<pre>{{ errorMsg | json }}</pre>
Now it works.

If you are trying to trim strings, you could use Javascript .trim() method.
var str = " Hello World! ";
alert(str.trim());
Output:
Hello world!
https://www.w3schools.com/jsref/jsref_trim_string.asp

Related

Render multiple Altair charts into a webpage

To create one webpage with multiple Altair charts, all nicely formatted and easily deployable to GitHub Pages, I am trying to get several tools to work together. I am rendering the charts' json into a markdown document with jinja and then using Hugo to convert the markdown to HTML. I am using a Hugo partial (in extend_head.html, shown below) to include the scripts for Vega, Vega-Lite, and VegaEmbed, and I see them in the HTML of the webpage.
extend_head.html
{{- /* Head custom content area start */ -}}
{{- /* Insert any custom code (web-analytics, resources, etc.) - it will appear in the <head></head> section of every page. */ -}}
{{- /* Can be overwritten by partial with the same name in the global layouts. */ -}}
{{- /* Head custom content area end */ -}}
{{- /* To render LaTex math */ -}}
{{ if or .Params.math .Site.Params.math }}
{{ partial "math.html" . }}
{{ end }}
<script src="https://cdn.jsdelivr.net/npm/vega#5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite#4.8.1"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed#6"></script>
I also have the following Hugo shortcode to call vegaEmbed. It includes the .Get method with a positional argument.
altairshortcode.html
<p>
<div id="vis"></div>
<script type="text/javascript">
var spec = {{.Get 0}}
vegaEmbed('#vis', spec);
</script>
</p>
The markdown template prior to rendering figure1's json looks like
---
title: "Aa1chart"
date: 2023-01-29T15:43:31-05:00
draft: false
---
Figure 1.
{{ '{{' }}< altairshortcode {{ figure1 }} >{{ '}}' }}
The Python code that's telling jinja to render the json into the template is (omitting the creation of the plot itself)
from pathlib import Path
from jinja2 import Template
# a scatter plot was generated with Altair and confirmed to display; omitted for brevity
p = Path.cwd()/'content/posts/aa1chart.md'
template = Template(p.read_text())
o = Path.cwd()/'content/posts/aa1chart.md'
o.write_text(template.render({
'figure1': figure1.to_json(),
}
)
)
After rendering the jinja template with the chart json, hugo runs, but hugo server -D, which launches a local server, gives the following error: unrecognized character in shortcode action: U+007B '{'. Note: Parameters with non-alphanumeric args must be quoted
After manually enclosing the json in double quotes, I got a different error unterminated quoted string in shortcode parameter-argument: '{
Some alternatives tried:
Using a named, instead of positional, parameter in the shortcode: Hugo runs, but hugo server -D errors: got quoted positional parameter. Cannot mix named and positional parameters. In the markdown, I had {{ '{{' }}< altairshortcode cjson={{ stage0 }} >{{ '}}' }}, and {{.Get "cjson"}} in the shortcode.
{{ .Inner }} converts the chart's json to a string, and so the chart does not appear in the webpage.
Placing Altair's figure1.to_html() instead of figure1.to_json() can display one chart in the webpage, but if multiple chart placeholders exist in the markdown, only one chart appears, and it is the last chart in the first position.
Looking at Hugo's built-in shortcodes, I hypothesize that if I utilized more logic or functions in my custom shortcode, such as toJSON, the json-to-string conversion can be prevented.

IntelliJ http client save JSON value as variable not working for variable names with - character

My GET Request:
### Bank token idclaim
GET {{IdClaimEndpoint}}/tokens/v1/id
Content-Type: application/json
> {% client.log(response.body.id-claim); %}
Response body:
{
"documentation": "http://go/proofs",
"id-claim": "eyJ0eXAiOiJKV1QiLCJhbGc"
}
Error from Response handler:
ReferenceError: "claim" is not defined. (<jsHandler script>#143)Script finished
If I try to extract value of documentation it works fine but not working for "id-claim".
I tried wrapping it within single/double quotes and also saving it to env variable and passing the env variable as {{id-claim}}, none of them worked.
It is JavaScript. You can use response.body['id-claim'] syntax. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#syntax
For example, the next request works fine:
POST https://httpbin.org/post
Content-Type: application/json
{
"my-json-value": "value"
}
{%
// 'json' is a property in HTTPBin response JSON
client.log(response.body.json["my-json-value"])
%}
This works:
> {%
client.log(JSON.stringify(response.body.valueOf()).replace("\"documentation\":\"http:\/\/go\/proofs\",\"id-claim\":\"", "").replace("\"","").replace("{","").replace("}",""));
client.global.set("banktokenidclaim", JSON.stringify(response.body.valueOf()).replace("\"documentation\":\"http:\/\/go\/proofs\",\"id-claim\":\"", "").replace("\"","").replace("{","").replace("}",""));
%}
But is a lot of work for a simple thing. Not sure if there exists a easier/better solution.

Code tag is not working in angular html template

I would like to display the below snippet in my html page. I'm using angular 2.
{path: 'test', component: TestComponent}
I've added below in my template to achieve this:
<pre>
<code>{path: 'test', component: TestComponent}</code>
</pre>
When I load the template, I see below error. How do I fix this? Can't I use code tag?
directive_normalizer.js:127 Uncaught Error: Template parse errors:
Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) ("
</ngb-tab>
</ngb-tabset>
</div>[ERROR ->]"): TestComponent#31:6
Invalid ICU message. Missing '}'. ("
</ngb-tab>
</ngb-tabset>
</div>[ERROR ->]"): TestComponent#31:6
The error Message provides the solution. Do the following:
<pre>
<code>{{"{path: 'test', component: TestComponent}"}}</code>
</pre>
Through interpolation it returns a string with the content.
Angular is trying to parse it as expression You have to escape the '{' braces as shown below.
<pre>
<code>{{'{'}}path: 'test', component: TestComponent{{'}'}}</code>
</pre>

ExpressJS/AngularJS : Converting JSON Object to String

I'm struggling with something that might be very easy, but hours of searching on Stackoverlow haven't helped.
I'm using Sir Trevor with MEANJS. Sir Trevor applies itself against a textarea field and saves its content as a JSON String.
Sir Trevor is saving its content to a field Content, which is set as an Object type in a Mongoose schema.
Creating works great and everything saves as expected.
However, when editing, the data doesn't come up correctly. The textfield is assigned data-ng-model="article.content" [the 'content' field from the model], but displays as [object Object], so when Sir Trevor tries to parse the value, it errors out.
I've tried using a directive with $formatters to change the value:
<textarea data-ng-model="article.content" id="content"
class="form-control st-instance" placeholder="Content" stRaw>
</textarea>
...and here is the directive:
articleApp.directive('stRaw', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
function stringIt(val) {
return JSON.stringify(val);
}
ngModel.$formatters.push(stringIt);
}
};
});
But it doesn't seem like the directive is ever triggered [I tried console.log within the link function and never saw anything].
I was able to make it work fine before by changing the schema type String and then using stringify over and over again within the code. This seemed sloppy, created undue bloat and also created challenges when trying to iterate through on an actual view page [it was seen as a String -- couldn't figure out how to parse].
I'm assuming I need to somehow catch the article.content attribute before it's rendered and change the value to a string. Is that the right direction?
There is typo in your html, the stRaw should be st-raw.
<textarea data-ng-model="article.content" id="content" class="form-control st-instance" placeholder="Content" st-raw></textarea>

How to run loop in JSON Template

In my application i'm using JSON Template for displaying content. I'm using conditional statements inside Template
{{#if document_id_1}} \
{{filename_1 }}
{{document_size_1}}
{{document_type_1}}
{{/if}}\
{{#if document_id_2}} \
{{filename_2 }}
{{document_size_2}}
{{document_type_2}}
{{/if}}\
................
i need to run loop (for or while) on this to avoid mentioning more if conditions in my code.
How can i run loop inside JSON Template???
Assuming Mustache and assuming all of the documents looks the same and assuming this structure
{
documents: [
{ filename: 'document_1', ... },
]
}
{{#documents}}
{{ filename }}
//other properties below
{{/documents}}