I have a template as under:-
<div class= "comment-form m-2">
{% include "includes/comment_reply_form.html" %}</div>
If the user is authenticated then the html shows the form. However if the user is not logged in I want to show a Login button. I am handling the same by the following javascript.
$(".comment-reply-btn").click(function(event){
event.preventDefault();
if (user_is_authenticated === false) {
$(".comment-form").html('{% include "includes/reply.html" %}');
$(this).parent().next(".comment-reply").fadeToggle();
}
else {
$(this).parent().next(".comment-reply").fadeToggle();
}
});
But, instead of including the html in from reply.html, it is showing {% include "includes/reply.html" %} in the webpage. There is no problem with the javascript and if I add
<p> You need to Login </p>
in the following line. It works fine :-
$(".comment-form").html('{% include "includes/reply.html" %}');
But since I need more options in my reply.html I want to add it as includes. I have tried using the escape character "/" in front of { but it didn't help.
not familiar but try
<div class= "comment-form m-2">
<script>
document.write('{% include "includes/comment_reply_form.html" %}')
</script>
</div>
Instead of putting the value from include in your javascript function just put it in the html with with display = none for example
<div id="comment-reply-form-template">
{% include "includes/comment_reply_form.html" %}
Then in your javascript you can always clone the already rendered form when you need to...
Or you could make a custom template tag that will print the html in javascript string style with a bunch of '' + '' + ''
or prehaps look into the new es6 template strings
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/template_strings
I think would work like
`{% include "includes/comment_reply_form.html" %}`
using the ` character
Related
I have a problem with HTMX in Django. I basically have two important components on page. List of categories and content that is being shown after you click on category.
I was working nicely with just standard htmx "out of the box". But I started having problems when I wanted to add active css class on category link after you click it (to show user where he is currently).
I did a lot of experiments with hx-swap-oob and hx-swap but the only thing that work was this:
(it is the most relevant part of the code)
<div class="col-sm-4">
<div class="card">
<div class="card-body" hx-boost="true" hx-target="#manual_results">
<div id="manual_categories">
{% include 'partials/manual_categories.html' %}
</div>
</div>
</div>
</div>
<div class="col-sm-8">
<div id="manual_results">
{% include 'partials/manual_entries_list.html' %}
</div>
</div>
and in manual_entries_list.html:
<some html results>
<div id="manual_categories" hx-swap-oob="true">
{% include 'partials/manual_categories.html' %}
</div>
Each category has simple if statement in django template code that is checking if it is selected (based on url path.)
And it is working, thing is, on the first request the categories are rendered twice (which is logical since I have 2 includes on the same HTML). After I select one category, everything goes back to normal because HTMX "starts to understand what is happening" and it switches the categories from manual_entries_list.html into our main page.
And like I said it works, I modified manual_entries_list.html to:
<some html results>
<div class="set_size_to_0px">
<div id="manual_categories" hx-swap-oob="true">
{% include 'partials/manual_categories.html' %}
</div>
</div>
So it is always invisible (so I will have only one set of categories visible).
The thing is, that it is an obvious hack. I am sure that there needs to be a better way of solving this problem but I cannot find it.
(I even tried to do it with plain javascript the thing is that categories are rendered in a for loop so it is pretty much impossible to get IDs correctly etc.)
Could someone please help me?
The easiest way to avoid this issue is to detect the HTMX request in the view function, pass this state to your templates and render HTMX content only if needed. HTMX will add a HX-Request: true header to each request.
For the detection you can use the Django-HTMX package that provides a request.htmx variable in your view functions that will be True if the request is coming from HTMX. Or if you want to check it manually:
def my_view(request):
is_htmx = request.headers.get('HX-Request') == 'true'
return render(request, 'my_template.html', {'is_htmx': is_htmx})
After that in manual_entries_list.html template include HTMX related stuff only in the HTMX requests:
<some html results>
{% if is_htmx %}
<div id="manual_categories" hx-swap-oob="true">
{% include 'partials/manual_categories.html' %}
</div>
{% endif %}
I am working with Hexo - a nodeJS based static blogging CMS, I am extending the hexo API to register a new block tag called tabblock, see here:
hexo.extend.tag.register('tabblock', function (args, content) {
var tabNumber = NumberOfTabs(content);
var isTabbed = (tabNumber !== 0);
console.log("Args: " + content);
// Where my proper logic should go
result = '<h1> TAG </h1>';
return result;
}, { ends: true });
This is the source snippet I am trying to interpret:
{% tabblock %}
``` JavaScript
console.log("Double Tap");
```
``` TypeScript
console.log("Double Tap");
```
{% endtabblock %}
However, the console.log from the function which should be processing that source, outputs this:
Args: <!--0--> <!--1-->
??? I Assume this is because the code is being interpreted as code rather than content? So if I wrap the {% tabblock %} in {% raw %} tags then I get no output at all, however, if I put the raw tags inside the tabblock, then I get this output:
Args: {% raw
How can I get my desired content?
\``` code ```\ is interpreted by Hexo as a code block, that why it output a messy thing. Try with only 2 or 1 backstick, it will works; like this \`` code ``\
I created a tabbed-codeblock tag for Hexo, you should take a look how I did it. As you can see, I wrapped code with the hexo tag and I use this structure to separate code blocks to avoid conflict with source code.
<!-- tab [lang] -->
code
<!-- endtab -->
<!-- tab [lang] -->
code
<!-- endtab -->
Gist : source code of tabbed code block tag + JS code to animate the component in the browser
SO Question - How to implement a tabbed codeblock tag for Hexo : because I created this tag for this question :p Read it, I explained the whole process :)
JSFiddle demo
I am loading a text from the DB of a django project to display it in the template.
In the text stored within the data base, I added some HTML tags but it seems like the browser cannot interprete this html tags.
Here is my template:
<div>
<!-- body_text = "<strong>Hello</strong> word" -->
{{ entry.body_text }}
</div>
And I got the raw text: <strong>Hello</strong> word instead of
<strong>Hello</strong> word
What I am doing wrong?
If you don't want your HTML to be escaped, use safe filter:
{{ entry.body_text|safe }}
django doc about safe filter.
You can also try this:
{% autoescape off %}
{{ your_html_content }}
{% endautoescape %}
From django docs for autoescape:
Controls the current auto-escaping behavior. This tag takes either
on or off as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with
an endautoescape ending tag.
When auto-escaping is in effect, all variable content has HTML
escaping applied to it before placing the result into the output (but
after any filters have been applied). This is equivalent to manually
applying the escape filter to each variable.
As pointed out in the other answer, you can also use safe filter which:
Marks a string as not requiring further HTML escaping prior to output.
When autoescaping is off, this filter has no effect.
See here: safe filter.
Read more about django template tags and filters: Django Built-in template tags and filters
I have some templates for my frontend code, like:
<div class="row">
<div class="my-header col-md-1">
<!-- comments -->
{{ title }}
</div>
<div class="my-container col-md-11">
{% if (content) { %}
{{ content }}
{% } else { %}
<p>Empty</p>
{% } %}
</div>
</div>
And I'm using grunt-contrib-jst to store them all in a single file and then on another build step will be included in a single JS file and that file is pushed to the CDN. This part is working perfectly, but I want to use the processContent option to minify the HTML template code, which contains Undercore template delimiters (<%...%> replaced with {% ... %}, <%= ... %> replaced with {{ ... }}).
I wanted to use html-minifier but it doesn't actually minimize anything, apparently because it tries to parse the template as HTML-only (and fails because of the templating tags).
Is there any Node package / function that allows me to minimize this kind of templates? I would like to use comments and whitespace in source templates but strip everything unnecessary on the resulting build file.
Right now I have this on my JST settings:
processContent: function (content) {
return content
.replace(/^[\x20\t]+/mg, '')
.replace(/[\x20\t]+$/mg, '')
.replace(/^[\r\n]+/, '')
.replace(/[\r\n]*$/, '\n');
},
...
But I want to minimize everything possible, that's why I tried with html-minifier.
Thanks!
I can't really help with minimising the underscore template delimiters, still trying to find out the best way to do that myself, but you might want to consider running your templates through htmlclean. I use it with r.js and it works really well for stripping out newlines and spaces in the code. Example usage:
var htmlclean = require('htmlclean');
// ...
processContent: function (content) {
return htmlclean(content)
.replace(/^[\x20\t]+/mg, '')
.replace(/[\x20\t]+$/mg, '')
.replace(/^[\r\n]+/, '')
.replace(/[\r\n]*$/, '\n');
},
I've had no problems with using this on HTML that has underscore templates in there. I hope it helps you.
I just have a question about how to achieve DRY with javascript that generates html on the fly. I have a list of elements that are loaded dynamically and populated by the django template a la
{{ tag.title }}
{% if request.user.is_authenticated %}
<a name="del-tag" data-id="{{ tag.id }}" class = "tag-x" title="Remove Tag" href="#">x</a>
{% endif %}
Now, I have some javascript that also loads new tags via ajax. Here's the relevant portion:
var newTag = "<span class = \"tag\">" + tagName + "<a name=\"del-tag\" data-id=\"" + tag_id + "\"" +
"class = \"tag-x\" title=\"Remove Tag\" href=\"#\">x</a></span>";
$('#tags').append(newTag);
Can I avoid duplicating HTML in the javascript?
Thanks.
jQuery Template could be used for this.
jquery(I'm assuming that's jquery that you are using) has a clone feature that can clone DOM elements. Given that you should be able to clone one of the html elements that already exist and change the value of the attributes, and then append it back to the DOM. I have not done this myself but it should work in theory.
Yes, you can do this. Have all tags generation functionality in a separate template. Then have some url which generates tags. Like this:
www.example.com/tags/?tags=tag1,tag2,tag3
this produces:
Then, when doing the AJAX call in your code do something like this:
$('div.tags').load('www.example.com/tags/?tags=tag1,tag2,tag3')
On the Django/template side you'd want to find a way how to include the result returned by the URL into the page template body. I'm not exactly sure what tools Django template engine provides, but on the first view it looks like you could put this code into some view method and extend this view everywhere you need it, providing the template variable as following render(..., tags=self.generate_tags(args)), in template it would be just {{ tags }}.
Both /tags/?tags=... and regular page /page/calls could re-use the generate_tags() method then.
Hope it helps