I have a list.gsp which loads a template .
Actually the template contains which loads the data from the domain class.
Every 10 seconds I want to refresh the template only, so that it gets latest data from the db. How can i do this?
There are several ways to solve this but all of them require Ajax. I'll give one example:
Suppose the following HTML:
<div class="content">
... other content here
<div id="template">
<g:render template="someTemplate" ... />
</div>
... other content here
</div>
Then this javascript:
setInterval(refreshTemplateEveryTenSeconds, 10000);
function refreshTemplateEveryTenSeconds() {
$('#template').load("/some/server/resource");
}
See the jquery load docs for more info on this.
Obviously, if you're not using jQuery then modify to do the ajax call as your technology would suggest. But this gives you a general idea of how you might approach the problem.
Related
I Want to develop a flask navigation bar like Google Contacts.
I Want to Render a particular HTML page inside the red box (as in the picture) when I click each of the navigation buttons (the green box as in picture) without refreshing the page.
I have already tried using
{% extends "layout.html" %}
As #Klaus D. mentioned in the comments section, what you want to achieve can be done using Javascript only. Maybe your question were
How can I send a request to my server-side (to get or fetch some information) and receive back a response on the client-side without having to refresh the page unlike the POST method usually does?
I will try to address the aforementioned question because that's probably your case.
A potential solution
Use Ajax for this. Build a function that sends a payload with certain information to the server and once you receive back the response you use that data to dynamically modify the part of the web-page you desire to modify.
Let's first build the right context for the problem. Let's assume you want to filter some projects by their category and you let the user decide. That's the idea of AJAX, the user can send and retrieve data from a server asynchronously.
HTML (div to be modified)
<div class="row" id="construction-projects"></div>
Javascript (Client-side)
$.post('/search_pill', {
category: category, // <---- This is the info payload you send to the server.
}).done(function(data){ // <!--- This is a callback that is being called after the server finished with the request.
// Here you dynamically change parts of your content, in this case we modify the construction-projects container.
$('#construction-projects').html(data.result.map(item => `
<div class="col-md-4">
<div class="card card-plain card-blog">
<div class="card-body">
<h6 class="card-category text-info">${category}</h6>
<h4 class="card-title">
${item.title_intro.substring(0, 40)}...
</h4>
<p class="card-description">
${item.description_intro.substring(0, 80)}... <br>
Read More
</p>
</div>
</div>
</div>
`))
}).fail(function(){
console.log('error') // <!---- This is the callback being called if there are Internal Server problems.
});
}
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Flask (Server-side)
''' Ajax path for filtering between project Categories. '''
#bp.route('/search_pill', methods=['POST'])
def search_pill():
category = request.form['category']
current_page = int(request.form['current_page'])
## Search in your database and send back the serialized object.
return jsonify(result = [p.serialize() for p in project_list])
Thank you #CaffeinatedCod3r,#Klaus D and #newbie99 for your answers.
I Figured it out. instead of using Flask we can use Angular JS Routing for navigation.
Here is the example that i referred:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<head>
<base href="/">
</head>
<body ng-app="myApp">
<p>Main</p>
Banana
Tomato
<p>Click on the links to change the content.</p>
<p>Use the "otherwise" method to define what to display when none of the links are clicked.</p>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/banana", {
template : "<h1>Banana</h1><p>Bananas contain around 75% water.</p>"
})
.when("/tomato", {
template : "<h1>Tomato</h1><p>Tomatoes contain around 95% water.</p>"
})
.otherwise({
template : "<h1>Nothing</h1><p>Nothing has been selected</p>"
});
$locationProvider.html5Mode(true);
});
</script>
</body>
</html>
By Using $locationProvider.html5Mode(true) i was able to remove the # from the URL.
I have a django setup which does not include any models or data base. It is just simple HTML, JAVAscript and python. It seems like django is not cleaning up the previous run data. How to cleanup data from forms after every run? I am not making use of sessions also. I am new to django and don;t have much time to learn sessions and implement things. Can any one give a solution on how to cleanup data after every run?
Use clear method to remove dictionary elements. Because django holds old values too. Not sure why, but this isn't the case with normal python scripts.
you have to clean the form via javascript than. The code below might get you some idea.
<body>
<form id="newForm">
Student Name<br><input type="text" name="sname"><br>
Student Subject<br><input type="password" name="ssubject"><br>
<input type="button" onclick="clear()" value="Submit">
</form>
<script>
function clear() {
document.getElementById("newForm").reset();
}
</script>
I've been playing around with golang for a couple of weeks now, and recently started to look into the revel framework.
In other languages/frameworks that I've used, it's always been possible to check what the current route is from within the template. Something that made it easier for me to keep things like navigation in a separate template file, and just do this:
<!-- in header template -->
<ul class="nav">
{{ if eq .req.action "App.Index" }}
<li class="active"><a href="#">
{{ else }}
<li><a href="{{url "App.Index" }}">
{{end}}
Home</a></li>
<!-- other links here -->
</ul>
This isn't the actual code I'm writing, but I hope this makes it clear what the idea is: Have a template for the navigation handy, and set classes/links according to which action is the current one.
After some time going through the source code, and a number of golang template examples, I couldn't quite see any way in which the current action or anything else is exposed to the template.
To get around this, I'm currently using a func interceptor which automatically sets a render argument for me:
func prependRoute(c *revel.Controller) revel.Result {
c.RenderArgs["_current_route"] = c.Action
return nil
}
This is working fine, but it feels a bit hacky. I think I'm probably missing something really obvious that would allow me to reserve func interceptors for when I really need them.
The question, then, is simple: What is the correct, and most reliable way to find out what the current action is in a revel template?
Being a frontend dev familiar with Ruby, i'm trying to learn Django templating system.
It appears to be an inside-out version of what i'm used to. I struggle to comprehend its reverse ideology: instead of declaring reusable blocks and including them where necessary, in Django you mark some parts of your template as overridable.
Here are two things that i don't understand about this.
With Ruby's Padrino, i would declare a partial (a reusable snippet of templated HTML) and then include it in multiple places. Wherever i call it, it would output its HTML.
According to Django's templating documentation, each block can be used on a page only once: Finally, note that you can’t define multiple block tags with the same name in the same template.
Another feature of Padrino that i find extermely useful is that partials can accept HTML and output (yield) it in a certain place inside them. Below are a couple examples, one for Padrino and one for Jade.
Please note that partails HTML not as a string (awkwardly passed via an argument) but in a template language via nesting.
Padrino (Ruby) example
With Padrino i can pass HTML template code into partials:
_container.erb
<div class="container <%= myclass %>">
<div class="container-inner">
<%= yield %>
</div>
</div>
layout.erb
<%= partial 'container', locals: { myclass: 'container--header' } do %>
<h1><%= Sitename %></h1>
<p>Welcome to my humble place</p>
<% end %>
Resulting HTML
<div class="container container--header">
<div class="container-inner">
<h1>Sitename</h1>
<p>Welcome to my humble place</p>
</div>
</div>
Jade example
In Jade, partials are called mixins and are processed directly by the template engine rather than the backend framework:
Jade source
mixin article(title)
.article
.article-wrapper
h1= title
if block
block
else
p No content provided
+article('Hello world')
p This is my
p Amazing article
Resulting HTML
<div class="article">
<div class="article-wrapper">
<h1>Hello world</h1>
<p>This is my</p>
<p>Amazing article</p>
</div>
</div>
Is it possible with Django?
Questions:
How do i reuse a block multiple times in Django? I would like to declare a snippet of template code and include it in multiple places on the page.
How do i pass HTML (template code) into a block? I would like to reuse it with different content.
The use case that i'm trying to cover is a reusable partial/mixin/block that would serve as a container wrapper for each section of the site.
Note that with Padrino, i can even make the partial in such a way that it will let me choose which wrapper tag (div, nav, header...) should be used for each instance of the partial, by passing an argument when including the partial:
<% partial 'container', myclass: 'container--header', tag: 'nav' %>
I wonder how to do that with Django.
In your answer, please comment on whether it is possible with both a) basic Django functionality; b) some Django extensions.
Thank you.
I’m not familiar with Padrino, so I’m not 100% sure I understand what you’re looking for.
However, Django template blocks definitely aren’t the equivalent of Padrino’s partials. From your description, I think the equivalent would be custom template tags.
In outline, to create a custom template tag, you:
Create a templatetags module within your Django app, with a file in it to contain the Python code for the tags e.g.
yourapp/
models.py
templatetags/
__init__.py
mytemplatetags.py
Within that file, create a variable called register that’s an instance of django.template.Library:
# mytemplatetags.py
from django import template
register = template.Library()
Within that file, write a function for each custom tag that you want.
For a tag that includes a template snippet, you’d want to write an inclusion tag.
Inclusion tags can take arguments, which could include HTML (but only as a string).
I'm trying to develop a reporting system using Django. I have to display reports about various categories of data.I have put each category as a tab-tab1,tab2, etc. Is it possible to have different template for each tab without having to change the url.
I have tried template inheritance but that requires have separate url for each tab.
My concern is that if the number of tabs grow, then the number of urls will also increase.
Any suggestions please?
Thanks in Advance.
Why is it a problem for the number of URLs to increase?
Presumably you don't need separate URLconf entries for each tab, you can just capture the tab name in the URL and send it on to the view:
url(r'^reports/(?P<tab_name>\w+)/$', views.reports, name='reports')
...
def reports(request, tab_name):
... do something depending on tab_name ...
You can just use {% include %} tag and include different templates.
And I think it's better to have unique URL for each tab, it least with hashtag.
You can use a library like jquery tabs to create the tabs, then load each template individually either through include as suggested by #DrTyrsa or by a custom template tag (which would be my personal preference).
Here is an example (from the excellent bootstrap framework from twitter):
<ul class="tabs">
<li class="active">Home</li>
<li>Profile</li>
<li>Messages</li>
<li>Settings</li>
</ul>
<div class="pill-content">
<div class="active" id="home">...</div>
<div id="profile">...</div>
<div id="messages">...</div>
<div id="settings">...</div>
</div>
<script>
$(function () {
$('.tabs').tabs()
})
</script>