Modify Image Url Value with Vue Js in a Loop - javascript

I have a simple Loop with conditionals. I want to modify the full url to a version of the image with 60x60 pixels.
Full image url : www.example.com/img/full-image-001.jpg .
Modified image url that I need : www.example.com/img/full-image-001-60x60.jpg .
<template v-else-if="column === 'product_img'">
<img :src="replaceLink.columnValue" alt="" height="60" width="60">
</template>
Method function:
methods : {
replaceLink (record) { //logic
}
}
EDIT :
Is this the proper way ?
methods: {
replaceLink (record) {
let res = record.replace(".jpg", "-60x60.jpg");
console.log(res);
}
},

Better solution is to create filter and use it on your images.
Instead fo methods object create filters object with replace function:
filters: {
replaceLink: function(value) {
if (!value) return '';
return value.replace('.jpg', '-60x60.jpg');
}
}
And now in your HTML you can use it like this:
<img :src="source | replaceLink" />
You should have source in your component data or you will get an error. This source should be image url

Related

Angular - Use a default image if image does not exist on server

I have a component that will display a cover image. The user can upload a cover image and the component will display the user uploaded image. If the user doesn't upload an image, then I want to display a default image.
If there is no user uploaded image I want to return an error and call the changeSource(event), which should in theory bind a new image url to the img src. However I'm getting undefined for the event.target.src and I'm seeing a blank space where the default image should be. It works fine when displaying the custom image.
component.html
<div *ngFor="let coverPhoto of coverPhotos">
<img src="{{coverPhoto}}"
(error) ="changeSource($event)" />
</div>
component.ts
this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
this.coverPhotos = result;
}, error => {
this.errors = error;
this.changeSource(event);
}, () => {
}
);
changeSource(event) {
event.target.src = "https://imageurl";
}
directly use (where defaultImage is a variable in ts file which holds the default image path) -
(error)="$event.target.src = defaultImage"
your HTML -
<div *ngFor="let coverPhoto of coverPhotos">
<img src="{{ coverPhoto }}" (error)="$event.target.src = defaultImage" />
</div>
Working example here.
You are passing event from this code in ts, which is obviously undefined, and you don't need to call this function from here -
this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
this.coverPhotos = result;
}, error => {
this.errors = error;
this.changeSource(event);
}, () => {
}
);
The *ngFor was throwing it off. Removing this seemed to solve the problem. Not quite sure why so will post an edit when I discover why.
<div>
<img src="{{coverPhotos}}"
(error)="$event.target.src = defaultImage" />
</div>

Using an imported image based on json data character name

I am getting data from a json file and when I get the character name of the object i'd like the div to render an image from an image I had imported. But when I use src={char} and say for example the char from the json file is 'sage' i'd like to use the sage image. But doing this method does not work like that. Also I am successfully getting the data from the json file so no problems on that end.
Thanks!
import sage from '../../assets/images/agents/sage_thumb.webp';
import viper from '../../assets/images/agents/viper_thumb.webp';
import jett from '../../assets/images/agents/jett_thumb.webp';
import valorant_rank from '../../assets/images/ranks/valorant.png';
const renderBody = () => {
return matchData && matchData.map(({ id, char, name, roundsPlayed, performance, multiKills, team }) => {
return (
<tr key={id} className='tr-background'>
<td className='match-table__agent-cell'><img className='img-fluid' src={char} alt="" /></td>
</tr>
)
})
}
I would use an object to map the agent name to its image url
const imageByAgent = {
sage: "../../assets/images/agents/sage_thumb.webp",
viper: "../../assets/images/agents/viper_thumb.webp",
...
}
And for the image src you can fetch the url using the character name
<img className='img-fluid' src={imageByAgent[char]} alt="" />

Gutenberg javascript get media srcset

In WordPress it is easy to get an images srcset and sizes as saved in WordPress using the wp_get_attachment_image_srcset function. I need to have that functionality on the block-editors side in javascript / react. Is that possible?
What I expect is a function that accepts a media id and returns the srcset somehow. If that is not possible, how could I implement a rest api endpoint for doing that? Or is there another way to pipe the function values from php to js?
For some reasons which are not relevant here, I cannot use dynamic php blocks.
I've share my solution here because I've see this post by searshing a solution for a similar problem : I was looking for a solution to get the srcset attribute and the complete generated 'img' tag but from the 'media' object returned by MediaReplaceFlow component (not only by attachment ID). It's probably adaptable to your problem by getting the media object with wp.data.select( 'core').getMedia(media_id).
This media object already contain a 'sizes' array with URL of image in some image sizes. but it's not sufficient because it's hard to build srcset ans size attribute for image tag. So, after many research, I've found a very helpfull php filter : wp_prepare_attachment_for_js
so with this filter, I've writed this PHP code :
function imageTagForJs( $response, $attachment ) {
foreach ( $response['sizes'] as $size => $datas ) {
$response['sizes'][$size]['tag'] = wp_get_attachment_image( $attachment->ID, $size );
$response['sizes'][$size]['srcset'] = wp_get_attachment_image_srcset( $attachment->ID, $size );
}
return $response;
}
add_filter( 'wp_prepare_attachment_for_js', 'imageTagForJs', 10, 2 );
Now, in the 'media' JS object, each sizes get two new properties : tag and srcset. I can now get my img tag in js by simply using media.sizes.medium.tag.
Important : By default, media.sizes array contain only builtin image sizes (thumbnail, medium, etc) but not custom image sizes. You can simply add custom sizes by using image_size_names_choose filter.
You can create an AJAX request that will be calling the wp_get_attachment_image_srcset on an attachment ID and return the result.
This example uses jQuery from the default "Twenty Seventeen" theme
Inside the child theme functions.php we define the AJAX WP method:
add_action("wp_ajax_get_attachment_image_srcset", "get_attachment_image_srcset");
add_action("wp_ajax_nopriv_get_attachment_image_srcset", "get_attachment_image_srcset");
function get_attachment_image_srcset() {
// Get attachment ID from the request
$attachment_id = $_REQUEST['attachment_id'];
// Get attachment srcset
$srcset = wp_get_attachment_image_srcset($attachment_id);
// Return JSON with the srcset and the attachment_id
wp_send_json([
'srcset' => $srcset,
'attachment_id' => $attachment_id
]);
}
Inside Block Editor, you can add a custom HTML block using AJAX to fetch the attachment srcset using an attachment ID.
Block Editor custom HTML code block:
jQuery(function($) {
// On a button click
$('.get-srcset a').on('click', function() {
// Get the value of a text input to pass as attachment ID
let attachmentId = $('#attachmentid').val();
// Make the AJAX call
jQuery.ajax({
type : "post",
dataType : "json",
url : '/wp-admin/admin-ajax.php',
data : {
action: "get_attachment_image_srcset",
attachment_id : attachmentId
},
success: function(response) {
// If we got an srcset
if(response.srcset) {
// Update the result element text with trhe srcset value or use srcset
$('#result').text(response.srcset);
}
else {
alert("No srcset")
}
}
});
});
});
This will update the #result element text to something like this:
https://wp.lytrax.net/wp-content/uploads/2020/04/3_ser_conv07-300x225.jpg 300w,
https://wp.lytrax.net/wp-content/uploads/2020/04/3_ser_conv07-768x576.jpg 768w,
https://wp.lytrax.net/wp-content/uploads/2020/04/3_ser_conv07.jpg 832w
You can check this working on this demo WP site: https://wp.lytrax.net/test-attachment-srcset/ (Valid attachment IDs are 5, 6, 7, 8, 9, 10)
Im using this
import { get } from 'lodash';
import { select, useSelect } from '#wordpress/data';
const image = useSelect( () => select( 'core' ).getMedia( id ) );
and lodash
const thumbnail = get( image, [ 'media_details', 'sizes', 'medium', 'source_url' ] );
For more: https://github.com/WordPress/gutenberg/blob/trunk/packages/block-library/src/image/image.js#L90
TO get the featured image first you need featured image id and then pass it to the getmedia function to get the media object. after getting media object you can get relevant items from the object.
const featuredImageId = wp.data.select( 'core/editor' )
.getEditedPostAttribute( 'featured_media' );
const media = featuredImageId
? wp.data.select( 'core').getMedia( featuredImageId )
: null;
console.log(media);

concat src img with condition in angular

i try to show image of users in template angular from api call .So if the image is emty i will show any other img but if image is null i should make condition in src img :
<img [src]="element.img!= null ? 'http://api.pointeuse.clediss.online/{{element.img}}' :
'https://img2.freepng.fr/20180523/tha/kisspng-businessperson-computer-icons-avatar-clip-art-lattice-5b0508dc6a3a10.0013931115270566044351.jpg'"
class="img-thumbnail border-0" />
the problem is i need to concate {{element.img}} with my base url
Use a get method.
.html:
<img [src]="imageUrl"/>
.ts:
get imageUrl(): string {
return this.element.img != null ? `some_url/${this.element.img}` : `other_url`;
}
In your .component.ts file, make this a computed property is one approach
get elementImage(): string {
if (this.element.image !== null) {
return `http://api.pointeuse.clediss.online/${this.element.image}`
} else {
return 'https://img2.freepng.fr/20180523/tha/kisspng-businessperson-computer-icons-avatar-clip-art-lattice-5b0508dc6a3a10.0013931115270566044351.jpg'
}
in your template, it would be
<img [src]="elementImage" class="img-thumbnail border-0" />

retrieving images from data return in vuejs

im trying to display som images in my code , already stored in my data in this way:
<div >
<tr v-for='(ships,index) in destroyedShipBox' :key='index'>
<td>{{ships}}</td>
<div v-for='(links,index1) in destroyedShipBoximages' :key='index1'>
{{links.type==ships?links.src:''}}
</div>
</tr>
</div>
where my data stores this arrays of objects:
data() {
return {
destroyedShipBox:['PatrolBoat','Destroyer'],
destroyedShipBoximages:[
{type:'PatrolBoat',src:require('../assets/patrolBoatHorizontalView.png')},
{type:'Submarine',src:require('../assets/submarineHorizontalView.png')},
{type:'BattleShip',src:require('../assets/battleshipHorizontalView.png')},
{type:'Carrier',src:require('../assets/carrierHorizontalView.png')},
{type:'Destroyer',src:require('../assets/destroyerHorizontalView.png')},
],
}
the destroyedShipBox gets fill automatically with some JSON already fetched then destroyedShipBoximages is just a collection of all type of ships in game as well as a image of its according to its type.
Thus my logic in the html template wants to set an image attuning with the kind of ships i already got in the destroyedShipBox array , but the the final result is this
PatrolBoat /img/patrolBoatHorizontalView.63b25d8d.png----->should be an image instead of this
Destroyer /img/destroyerHorizontalView.396ed25f.png ----->should be an image instead of this
simply the image don't appear...
Any advice about how to solve this problem...
thanks in advance!!!!
you can also ease up your template logic and have only one if condition if there is a 1:1 relation between ships and their images with the following computed property:
computed: {
shipsWithImages() {
return this.destroyedShipBoximages.filter((value) => {
if(this.destroyedShipBox.includes(value.type)) {
return value;
}
})
},
}
Cheers,
ewatch
You should assign links.src to src attribute of img tag like this:
<div>
<tr v-for='(ships,index) in destroyedShipBox' :key='index'>
<td>{{ships}}</td>
<td>
<div v-for='(links,index1) in destroyedShipBoximages' :key='index1'>
<img :src="links.src" v-if="links.type==ships"/>
</div>
</td>
</tr>
</div>

Categories