Can I use Rust / Yew / Trunk to generate just a DOM node and script for use in HTML templates? - html

TLDR
Total n00b with rust, yew and trunk.
I want to find out how to rust, yew and trunk to build an HTML file containing just one DOM node, not a whole HTML page.
Background
Day-to-day, I use Django, the python web framework. Its admin console uses HTML template rendering, and an example of a template might look like this:
{% extends 'django_twined/question_changeform.html' %}
{% block object-tools-items %}
{% if show_set_active %}
<li>Set active</li>
{% endif %}
{{ block.super }}
{% endblock %}
Where in this example the {% %} and {{ }} get evaluated at render time into a valid HTML structure (from other template files), and the <li> is an extra node that gets added to the DOM.
Instead of a vanilla li element, I want to build a complex DOM node using Rust/Yew/Trunk. Then I can include the resulting head and body elements file in a django template, something like:
{% extends 'django_twined/question_changeform.html' %}
{% block head %}
{{ block.super }}
<!-- Include the scripts generated by trunk build -->
{% include 'my-dom-node-head.html' %}
{% endblock %}
{% block object-tools-items %}
<!-- Include the elements generated by trunk build -->
{% include 'my-dom-node-body.html' %}
{{ block.super }}
{% endblock %}
Where I'm at
I've used the yew starter app to get myself to an app. The input index.html is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Yew App</title>
</head>
</html>
And the main.rs file looks like:
use yew::prelude::*;
enum Msg {
AddOne,
}
struct Model {
value: i64,
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
value: 0,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::AddOne => {
self.value += 1;
// the value has changed so we need to
// re-render for it to appear on the page
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
// This gives us a component's "`Scope`" which allows us to send messages, etc to the component.
let link = ctx.link();
html! {
<div>
<button onclick={link.callback(|_| Msg::AddOne)}>{ "+1" }</button>
<p>{ self.value }</p>
</div>
}
}
}
fn main() {
yew::start_app::<Model>();
}
After trunk build, the output index.html looks like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Yew App</title>
<link
rel="preload"
href="/yew-app-caccf6c60742c530_bg.wasm"
as="fetch"
type="application/wasm"
crossorigin=""
/>
<link rel="modulepreload" href="/yew-app-caccf6c60742c530.js" />
</head>
<body>
<script type="module">
import init from "/yew-app-caccf6c60742c530.js";
init("/yew-app-caccf6c60742c530_bg.wasm");
</script>
</body>
</html>
Where next?
So basically I need to get the <link> and <script> elements added by trunk build and put them into my template.
What should I do next? Would you suggest I try to:
Get trunk build --filehash false to output deterministic .js and .wasm file names without the hash (caccf6c60742c530 in this case) so that I can directly write the includes into my template (I'm concerned this will cause me development problems down the road)?
Get trunk build to output separate head link and body script?
Post-process the output index.html to extract the inserted scripts?
Alter main.rs in some way to output only what I need/want?

Related

Eleventy / Nunjucks: minify JS with terser within minified HTML

I try to minify partial HTML in which I minify some JS using terser (using a jsmin filter as showed in 11ty docs):
<!doctype html>
<html lang="fr"><head><meta charset="utf-8"><title></title></head>
{% set html %}
<body>
<div class="foo">
Bar
</div>
<script>{% set js %}
var foo = 'foo',
bar = 'bar';
{% endset %}{{ js | jsmin | safe }}</script>
{% endset %}
{{ html | htmlmin | safe }}
</body>
</html>
But since the terser process is asynchronous, it throws an error in 11ty (callback is not a function, and <script>[object Promise]</script> in the generated file).
Same problem if I try to minify all the HTML using an 11ty transform (as suggested in their docs: Minify HTML Output – and removing all the {% set html %} / {{ html | … }} tags): it throws some similar Promise errors (Having trouble writing template … Cannot read properties of undefined … at async Promise.all)
Problem solved if I move the script part outside of the Nunjucks set declaration:
<!doctype html>
<html lang="fr"><head><meta charset="utf-8"><title></title></head>
{% set html %}
<body>
<div class="foo">
Bar
</div>
{% endset %}
{{ html | htmlmin | safe }}
<script>{% set js %}
var foo = 'foo',
bar = 'bar';
{% endset %}{{ js | jsmin | safe }}</script>
</body>
</html>
But that's not what I want.
Trying to make terser synchronous seems to need some more npm packages so I'm hoping there's an easier way before trying it.
Edit: tried to use html-minifier-terser instead of html-minifier, with this code for the htmlmin filter:
const TerserHTML = require('html-minifier-terser');
…
eleventyConfig.addNunjucksAsyncFilter('htmlmin', async function(code, callback) {
try {
let minified = await TerserHTML.minify(code, {
removeComments: true,
collapseWhitespace: true
});
callback(null, minified);
} catch (err) {
console.error('Terser HTML error: ', err);
callback(null, code);
}
});
→ same issue

How can I iterate through each item in a database and display them in divs on my html page with django?

I have some code written to find the first post in the database and output it to my page, but I', not sure how to go about iterating through the database. I've done similar things before but this is my first time using django and bootstrap.
My view currently looks like this:
def gallery_view (request):
obj = GalleryPost.objects.get (id =1)
context = {
'object' : obj
}
return render(request, "gallery.html", context)
This works well enough for 1 object but as you can see it takes a set ID of 1, so I need to somehow iterate this to fetch every item from my DB and somehow output them properly.
View:
def gallery_view(request):
qs = GalleryPost.objects.all()
context = {
'objects' : qs
}
return render(request, "gallery.html", context)
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for object in objects %}
<div>
{{object}}
</div>
{% empty %}
<p>No objects found</p>
{% endfor %}
</body>
</html>
Instead of .all() you can also use .filter() to filter the queryset.

How to add custom view in django adminlte?

I created an environment using pycharm & installed adminlte by git clone from https://github.com/app-generator/django-dashboard-adminlte.git. And installed adminlte3 , django3.1 & all requirements. Then run python manage.py runserver and registered a new user & was able to login ,view all pages, added new link to a html page. But I am unable to add view with jsonresponse to a button click on new page, geting Error 500 - Server Error.
My new html page is
{% extends "layouts/base.html" %}
{% block title %} Layout Boxed {% endblock %}
<!-- Element injected in the BODY element -->
{% block body_class %} sidebar-mini layout-boxed {% endblock body_class %}
<!-- Specific Page CSS goes HERE -->
{% block stylesheets %}
<!-- Google Font: Source Sans Pro -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
<!-- Font Awesome -->
<link rel="stylesheet" href="/static/assets/plugins/fontawesome-free/css/all.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="/static/assets/css/adminlte.min.css">
<link rel="stylesheet" href="/static/assets/css/mapstyle.css">
<link rel="stylesheet" href="/static/assets/js/pages/gis/dist/map.css">
<style>
.map {
margin: 0;
padding: 0;
width: 900px;
height: 500px;
background:white !important;
border:1px solid #ccc;
}
</style>
{% endblock stylesheets %}
{% block content %}
<div class="content-wrapper">
<div id="lyrDiv"></div>
<div id="map" class="map"></div>
<button id="search">Search</button>
</div>
{% endblock content %}
<!-- Specific Page JS goes HERE -->
{% block javascripts %}
<!-- jQuery -->
<script src="/static/assets/plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="/static/assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="/static/assets/js/adminlte.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="/static/assets/js/demo.js"></script>
<script src="/static/assets/js/pages/map.js"></script>
<script src="/static/assets/js/pages/search.js"></script>
{% endblock javascripts %}
search.js
$( "#search" ).click(function() {
$.get('/search/',{'csrfmiddlewaretoken':csrftoken},function(data){
alert(data); // here getting Error 500 - Server Error
});
});
I added below line to /django-dashboard-adminlte/app/urls.py
re_path(r'^search/$', search.spatial_srch, name='search'),
and search.py
from app.models import *
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
#csrf_exempt
def spatial_srch(request):
data= Demotable.objects.all()
searchArr = []
output = {}
for c in data:
searchArr.append({'type': 'Feature', 'properties': {'id':c.id,'name': str(c.name)},'geometry': {'type': 'Point', 'coordinates': [c.the_geom.x, c.the_geom.y]}})
output = {'type': 'FeatureCollection', 'features': searchArr}
return JsonResponse(output)
When I click on the 'Serach' button the request is not going to the view search.py What is wrong in my code ? what configuration did I miss?
The post shows
The Error 500 shows only adminlte Error page. Nothing more
The problem is in the (not so nice) way they generate the error. It's anti-pattern hell there, but in short it means there's an except thrown in either:
finding the template
loading the template
or rendering the template
and they catch it and don't let you see what happened. Not very nice code and you're have to modify that file to even begin debugging it:
#login_required(login_url="/login/")
def pages(request):
context = {}
# All resource paths end in .html.
# Pick out the html file name from the url. And load that template.
try:
load_template = request.path.split('/')[-1]
html_template = loader.get_template( load_template )
return HttpResponse(html_template.render(context, request))
except template.TemplateDoesNotExist:
html_template = loader.get_template( 'page-404.html' )
return HttpResponse(html_template.render(context, request))
# Remove or comment these lines:
#except:
#
# html_template = loader.get_template( 'page-500.html' )
# return HttpResponse(html_template.render(context, request))
Also I'm not sure this the specific spot where the error is generated, they might be doing similar things in other places.
Edit
This is very .... unprofessional code:
# Matches any html file
re_path(r'^.*\.*', views.pages, name='pages'),
No, it doesn't not match any "html" file - it matches everything cause they don't get regular expressions:
^ - start of string
.* - anything or nothing
\.* - >>>zero<<< or more dots
Result: \.* is ignored as it is irrelevant so it matches everything and if you placed your re_path below it, it will never be consulted, because Django uses first match wins approach.
So your url matches theirs, which then routes it to pages view:
load_template = request.path.split('/')[-1]
Since request.path is '/search/', '/search/'.split('/')[-1] gives the empty string and that creates your problem.
I highly suggest fixing their url path:
# Matches any html file
re_path(r'\.html$', views.pages, name='pages'),
Or put your re_path above theirs.

Unable to render PIL object base64 image on template

I'm trying to display a PIL object after converting to base64.
I'm getting the base64 value in the src tag but the response is not rendered even after decoding
import base64
import io
def newrules(request):
pic = con(select.fname)
print(pic)
buffered = io.BytesIO()
pic.save(buffered, "PNG")
img_str = base64.b64encode(buffered.getvalue())
template_code = """
{% load static %}
<!DOCTYPE HTML>
<html>
<body>
{% block pagecontent %}
<div>
<img src="data:image/png;base64,{{ img_str }}">
</div>
<div>
{{ img_str }}
</div>
</body>
{% endblock %}
</html>
"""
template = engines['django'].from_string(template_code)
return HttpResponse(template.render(context={'img_str': img_str}))
HTML souce code
terminal API call responses
Template rendered
Any help will be highly appreciated.
base64.b64encode(buffered.getvalue()) returns a byte class object. It needs to be converted to a string before passing it to a template. It can be done as follows:
img_str = base64.b64encode(buffered.getvalue()).decode('ascii')

Slim 3 not rendering assets

So I'm trying to render my global stylesheet but I am getting an error
[Error] Did not parse stylesheet at 'http://localhost:8888/css/app.css' because non CSS MIME types are not allowed in strict mode.
Here is my code:
app.twig
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>App</title>
<link href="https://fonts.googleapis.com/css?family=Playfair+Display" rel="stylesheet">
<link rel="stylesheet" href="{{ base_url() }}/css/app.css">
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
index.twig
{% extends 'app.twig' %}
{% block content %}
Hello from {{ appName }}!
{% endblock %}
app.css
* { box-sizing: border-box; }
html, body {
font-family: 'Playfair Display', serif;
background: yellow;
}
As you can see in my structure the file is there screenshot
I've been looking to resolve this issue but can't see to find the fix, any help is appreciated.
You should configure your web server to parse and send the CSS file directly.
If you're using the built-in PHP web server, then add this to the top of index.php:
if (PHP_SAPI == 'cli-server') {
$_SERVER['SCRIPT_NAME'] = basename(__FILE__);
// To help the built-in PHP dev server, check if the request was actually for
// something which should probably be served as a static file
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
if (is_file($file)) {
return false;
}
}
If you're using Apache or Nginx, then look at https://www.slimframework.com/docs/start/web-servers.html