Adonis js Edge get domain url in assetUrl - adonis.js

Am sending an email via adonis mailer and i would like to get the domain name to include in the images on the edge files but am stuck on how to add the domain name as emails sent dont display the images
So in my email edge file i have
<html>
.....other stuff
<img
src="{{ assetsUrl('images/logo.png') }}"
/>
</html>
This doenst display the logo.
A quick check on the output of
{{assetsUrl('images/logo.png')}}
it displays
/images/logo.png
This shows that the domain name is not included i n the assetUrl helper.
How can i get the domain name in the edge file, so that the src propery is complete to display the image

I have a solution but it's not perfect :
You can use .env variables (example: APP_URL, or custom)
Edge:
<img src="{{ APP_URL() }}{{ assetsUrl('images/logo.png') }}"/>
You need to create start/hooks.js :
const { hooks } = use('#adonisjs/ignitor')
hooks.after.providersBooted(() => {
const Env = use('Env')
const View = use('View')
View.global('APP_URL', function () {
return Env.get('APP_URL')
})
})
Same issue : forum.adonisjs.com/t/grab-full-page-url/1998

For sending images in email, Adonis has functions for that.
const Helpers = use ('Helpers')
embed (filePath, cid, [options])
Embed an image into the HTML body using a content id:
message.embed (Helpers.publicPath ('logo.png'),
https://adonisjs.com/docs/4.1/mail

Related

How do I inject a template into another template in Flask [duplicate]

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.

Displaying Filepaths Correctly in Flask/Jinja2

I have a setup in a flask app where I can use a form to upload a file into the static/img directory for my application, and the metadata is stored in a record in a database.
When someone makes a request to the appropriate page, I want to read the file from the server using the filepath saved in the database.
Here's an example of the record when it's pulled from the database:
(3, 'My Info', 'My Description', 'www.url.com', 'static\\img\\aws_nameservers.PNG')
What I'd like to do is combine the last item in the above record with the url_for function to render the image stored at that location.
What I have right now is a set method that gets the last part of the file path:
{% set filepath = workshop_info[4][7:] %}
This returns img\\aws_nameservers.PNG
Then inside an img tag I have the following:
<img src="{{ url_for('static', filename=filepath) }}">
Which gives me the following result:
<img src="/static/img%5Caws_nameservers.PNG">
It seems like a simple thing, but I can't figure out how to render the string correctly inside the jinja2 template.
Thank you.
If there is a better approach than what I'm attempting, I'm happy to get corrected.
You should use the forward slash (/) instead of backslash (\) at the file path. You can replace them either in the Python code or in the template using a filter, e.g.:
{% set filepath = "img\\aws_nameservers.PNG" | replace("\\", "/") %}
{{ url_for('static', filename=filepath) }}
# Outputs: /static/img/aws_nameservers.PNG
You can also use the pathlib module to convert between the Windows and Unix style paths.

How to remove everything before provided value

I am using Bootstrap Vue and would like to use a formatter callback to insert html into a column inside the table. The Bootstrap documentation example formats the link as an anchor link
Ex. https://bootstrap-vue.js.org/docs/components/table/#shirley-partridge
<b-table striped responsive hover :items="episodes" :fields="fields">
<template v-slot:cell(version)="data">
<a :href="`${data.value.replace(/[^a-z]+/i,'-').toLowerCase()}`">{{ data.value }}</a>
</template>
</b-table>
I am pulling in a full url from the version property and would like to only use this url in the template, how can I remove everything before my url using the formatter?
this.episodes = response.map((item) => {
return {
category: item.fields.title,
episode_name: item.fields.splash,
episode_acronym: item.fields.description,
version: 'https://myurl/webinars' + item.fields.slug + '/' +'test',
}
})
Desired link would be https://myurl/webinars....
I was able to get this working, by keeping the relative url format, and updating the formatter with a - instead of a + sign
<a :href="`${data.value.replace(/[^a-z]-/i,'-').toLowerCase()}`">Definition</a>

how to view image in Django application

I need to view only the image in HTML page.
Like : http://localhost:8000/media/project_name/imagenav.jpg
Example page : https://s3-media3.fl.yelpcdn.com/bphoto/c7ed05m9lC2EmA3Aruue7A/o.jpg
Thanks & Regards,
Mohamed Naveen
It's simple
Your statics must be configured first.
{% load static%}
<br>
<img src = "{% static 'image name in static folder'%} " >
Check my site on heroku
http://pyworldpy.herokuapp.com

How to set the default directory for wysisyg editor insertImage in flask

I'm building a CMS in flask and I have built a simple wysiwyg editor using execcommands for creating and editing posts, and everything is working. For the insertImage command I'm using an input element to open a directory and choose an image. It works except of course it opens my computers default folder. I want it to open the uploads folder in the static directory where user images are stored in flask. How?
I have searched through flask docs, Python handling files documentation and there's no mention of this. This is a project I'm doing for a class. I'm going above and beyond the requirements for this project but that's how I keep things interesting. I mean it's supposed to be a CMS right. Well, CMS's always have wysiwyg's that open the default "uploads" folder to insert media. Also, when creating my upload functions I found that when uploading files flask needs the absolute path. But when serving them the relative path is necessary.
Any point in the right direction would be greatly appreciated. Thank you.
Here's the structure
<div class="col-md-1 tools">
<a href="#" data-command='insertImage'data-toggle="tooltip" title="Insert Media"><i class='material-icons'>add_photo_alternate</i>
</a>
<div class="editorInputs">
<input type="file" name="media" id="insertImage"
accept="audio/*,video/*,image/*"/>
</div>
</div>
Here's my js script
$('.tools a').mousedown(function(e){
let command = $(this).data('command');
if(command == 'insertImage'){
$(this).next().children('input').trigger('click');
let input = $(this).next().children();
input.on('change', function(e){
let val = $(input).val();
document.execCommand(command, false, val);
})
}
});
Here's how my uploads file is configured in flask
app.config['SITE_UPLOADS'] = 'D:/Courses/Development/Programming/Python/LaunchCode/LC101/unit2/build-a-blog/static/site/uploads/'
app.config['ADMIN_UPLOADS'] = 'D:/Courses/Development/Programming/Python/LaunchCode/LC101/unit2/build-a-blog/static/admin/uploads/'
app.config['ALLOWED_IMAGE_EXTENSIONS'] = ['PNG', 'JPG', 'JPEG', 'SVG', 'GIF']
app.config['DATA_FILES'] = 'D:/Courses/Development/Programming/Python/LaunchCode/LC101/unit2/build-a-blog/data/'
app.config['RELATIVE_PATH_SITE'] = '../static/site/uploads/'
app.config['RELATIVE_PATH_ADMIN'] = '/static/admin/uploads/'
So, I realized that I have to create a function to pull images from the uploads folder, display them, get their URL and pass it to the execcommand. And I did.
First, create the gallery structure with radio buttons to view files. Then put the gallery in a bootstrap modal to fire when the execccomand insertImage link is clicked. Grab the URL of the checked image. pass it to the execcomand function in my js.
On the flask side get a list of all files in the uploads directory with os.listdir(absolute/path/to/directory), returns a python list of the files. Next create file urls and put info in a dict by looping over the filenames in the list and adding the relative path to the filename. Pass the dict to the jinja2 template and populate the gallery.
Finally, execute the js.
Here's my python code and js code.
def get_uploads():
list_images = os.listdir(app.config['ADMIN_UPLOADS'])
images = []
i =0
length = len(list_images)
while i < length:
img = {}
img['name'] = list_images[i]
img['url'] = os.path.join(app.config['RELATIVE_PATH_ADMIN'], list_images[i])
images.append(img)
i+=1
return images
Here's my js.
if(command == 'insertImage'){
$("#uploadsGallery").modal();
$('.ftco-animate').addClass('fadeInUp ftco-animated')
let check = $(this).next().find('input.form-check-input');
let val;
check.on('change', function(e){
val = $(this).val();
});
$('#insertImg').click(function (e) {
r.setStart(editDiv, lastCaretPos);
r.setEnd(editDiv, lastCaretPos);
s.removeAllRanges();
s.addRange(r);
document.execCommand(command, false, val);
check.prop('checked', false);
});
}