How to display JSON Array in Blade view? - json

My db table structure
I'm using a view composer to get data from this table and send it back to my view
class NavComposer
{
public function compose(View $view)
{
if (Auth::check()) {
$view->with('unread_notifications', DB::table('notifications')->where([
['read_at', '=', NULL],
['notifiable_id', '=', Auth::user()->id],
])->get());
}
}
}
My view:
#foreach($unread_notifications as $notification)
{{ $notification->data }}
#endforeach
What I am getting:
{"id":79,"sender":"Diana","receiver":"Alex","subject":"Subject","body":"Lorem ipsum"}
What I want to display:
ID: 79
Subject: Subject
Body: Lorem Ipsum
I apologize in advance if this is very simple stuff I dont know much about JSON

You need to decode JSON. You can do this manually:
#foreach($unread_notifications as $notification)
<?php $notificationData = json_decode($notification->data, true); ?>
{{ $notificationData['sender'] }}
#endforeach
Or you can create accessor so Laravel could automatically convert JSON to an array:
public function getDataAttribute($value)
{
return json_decode($value, true);
}

#foreach($unread_notifications as $notification)
#foreach(json_decode($notification->data, true) as $d)
<div>ID: {{ $d['id'] }}</div>
<div>Subject: {{ $d['subject'] }}</div>
<div>Body: {{ $d['body'] }}</div>
#endforeach
#endforeach

Related

How to get properties of object from this HTTP response

I am trying to display the currency name or key like "USD", "AUD", "EUR" with their respective "last" and "buy" properties from this HTTP response:
and I just get back a list of "key" strings like this
but I can't figure out why my "key" is being returned as a string here.
It's making it difficult for me to programmatically access the properties for each currency
this is my dashboard.component.ts
prices;
bitcoinOwned;
ngOnInit(): void {
this.data.getPrice()
.pipe(map(result => {this.prices = result, console.log("result", result)
for (let key in result) {console.log( key)}
} ))
.subscribe();
}
my data.service
getPrice() {
var url = "https://blockchain.info/ticker";
return this.http.get(url);
}
and my template
<div>
{{ prices |json }}
</div>
<div>
USD last: {{ prices?.USD.last |json }} USD sell: {{ prices?.USD.sell |json }}
</div>
I can access the properties when I do it manually for each key like this but I need to iterate over the keys and do it more programmatically so any help would be appreciated!!
You may want to use Angular's KeyValuePipe.
Then, you can do something like this:
<div *ngFor="let item of prices | keyvalue">
{{item.key}} last: {{ item.value.last |json }} {{item.key}} sell: {{ item.value.sell |json }}
</div>
I think you can use Object.keys() on the object to return the key value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Displaying object into HTML in Angular

sorry for the noob question.
I created an http request and retrieved some pokemon data and put it in an object called pokemon, like so:
export class AppComponent implements OnInit{
title = 'Pokedex';
apiURL = 'https://pokeapi.co/api/v2/pokemon/1';
pokemon = {};
constructor(private http: HttpClient){}
ngOnInit(): void{
this.http.get(this.apiURL).subscribe(data =>{
const pokemon = {
name: data['name'],
id: data['id'],
abilities: data['abilities'].map( ability => ability['ability']['name']),
types: data['types'].map( type => type['type']['name']),
image: data['sprites']['front_default']
}
console.log(pokemon);
When I console log the object, it outputs in the console fine.
However, when I try to display it in an html {{ pokemon }} it just returns [object, Object]
How can I get around this?
I have tried the methods suggested below.
{{pokemon.name}}, {{pokemon[name]}} and {{pokemon?.name} display a blank page.
{{ pokemon | json }} returns an empty object, in the form of {}.
Am I perhaps doing something else wrong?
You need to use the json pipe
<pre>{{ pokemon | json }}</pre>
OR
<div> Id: {{ pokemon.id }} </div>
<div> Name: {{ pokemon.name }} </div>
<div> Abilities:
<ul>
<li *ngFor="let ability of pokemon.abilities"> {{ ability }}</li>
</ul>
</div>
<div> Types:
<ul>
<li *ngFor="let type of pokemon.types"> {{ types }}</li>
</ul>
</div>
call property as {{pokemon?.name}}
You can't use object directly. You have to access object properties by either . (Dot) notation or object[property] way.
In your case, if you want to use the property of name then use
{{ pokeman.name }}
or
{{ pokeman[name] }}

Angularjs web app error

The angularjs app doesn't show me any result.
It shows me :
Name City Order Total joined
{{ cust.name }} {{ cust.city }} {{ cust.orderTotal }} {{ cust.joined }}
What is the reason of this type of error !!!
Update 1:
function CustController($scope)
{
$scope.sortBy = 'name';
$scope.reverse = false;
$scope.customers = [
{joined: '240-344-55', name:'jone', city:'usa', orderTotal:'231'},
{joined: '240-344-55', name:'jone', city:'usa', orderTotal:'231'},
{joined: '240-344-55', name:'jone', city:'usa', orderTotal:'231'}
];
$scope.doSort = function(propName) {
$scope.sortBy = propName;
$scope.reverse = !$scope.reverse;
};
}
If you are using $scope approach, then you have to remove "cust." part from your view. It would be {{ name }} {{ city }} etc.
But if your view has ng-controller="CustController as cust", that means you are using "controller as" syntax, so you would need to refactor your controller code, changing $scope. to this. everywhere at least.

twig striptags and html special chars

I am using twig to render a view and I am using the striptags filter to remove html tags.
However, html special chars are now rendered as text as the whole element is surrounded by "".
How can I either strip special chars or render them, while still using the striptags function ?
Example :
{{ organization.content|striptags(" >")|truncate(200, '...') }}
or
{{ organization.content|striptags|truncate(200, '...') }}
Output:
"QUI SOMMES NOUS ? > NOS LOCAUXNOS LOCAUXDepuis 1995, Ce lieu chargé d’histoire et de tradition s’inscrit dans les valeurs"
If it could help someone else, here is my solution
{{ organization.content|striptags|convert_encoding('UTF-8', 'HTML-ENTITIES') }}
You can also add a trim filter to remove spaces before and after.
And then, you truncate or slice your organization.content
EDIT November 2017
If you want to keep the "\n" break lines combined with a truncate, you can do
{{ organization.content|striptags|truncate(140, true, '...')|raw|nl2br }}
I had a similar issue, this worked for me:
{{ variable |convert_encoding('UTF-8', 'HTML-ENTITIES') | raw }}
I was trying some of, among others, these answers:
{{ organization.content|striptags|truncate(200, true) }}
{{ organization.content|raw|striptags|truncate(200, true) }}
{{ organization.content|striptags|raw|truncate(200, true) }}
etc.
And still got strange characters in the final form. What helped me, is putting the raw filter on the end of all operations, i.e:
{{ organization.content|striptags|truncate(200, '...')|raw }}
Arf, I finally found it :
I am using a custom twig filter that just applies a php function:
<span>{{ organization.shortDescription ?: php('html_entity_decode',organization.content|striptags|truncate(200, '...')) }}</span>
Now it renders correctly
My php extension:
<?php
namespace AppBundle\Extension;
class phpExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('php', array($this, 'getPhp')),
);
}
public function getPhp($function, $variable)
{
return $function($variable);
}
public function getName()
{
return 'php_extension';
}
}
2022 update | tested with Drupal 8.6.16
I tried the top voted recommendation. It worked ok with some symbols but not with others.
raw filter seems to be working ok with all special characters.
like so
{{ organization.content|striptags|raw }}
The best way to do this is :
{{ organization.content|striptags|truncate(200, '...')|raw }}
With |raw always at the end.
Don't use convert_encoding('UTF-8', 'HTML-ENTITIES'), you will encounter iconv issues.
When I thought none of the above answers were working for me (convert_encoding running into iconv() issues in Drupal 9, and I thought raw, but because applying it on the argument side of an {% embed %} — as opposed to in the embedded template itself — didn't seem to help), another approach that seemed to work for me was:
{% autoescape false %}
{{ organization.content|striptags|truncate(200, '...') }}
{% endautoescape %}
with that false part being key.
I had the same problem, I resolved it byt this function below, using strip_tags.
<?php
namespace AppBundle\Extension;
class filterHtmlExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('stripHtmlTags', array($this, 'stripHtmlTags')),
);
}
public function stripHtmlTags($value)
{
$value_displayed = strip_tags($value);
return $value_displayed ;
}
public function getName()
{
return 'filter_html_extension';
}
}

following a tutorial notfoundhttpexception

i am pretty new to framework and laravel in general, im struggling to learn laravel, and i have found this book.
https://leanpub.com/learninglaravel
I hope is a good start. (usually i coded in php and html)
I have a problem following the basic tutorial (:/ not a good start lol)
Routes.php
Route::post('contact', function()
{
$data = Input::all();
$rules = array(
'subject' => 'required',
'message' => 'required'
);
$validator = Validator::make($data, $rules);
if($validator->fails()) {
return Redirect::to('contact')->withErrors($validator)->withInput();
}
return 'Your message has been sent';
});
Route::get('/', function()
{
return View::make('home');
});
Route::get('about', function()
{
return View::make('about');
});
Contact.blade.php
#extends('layout')
#section('content')
<h1>Contact Us.</h1>
<p>Please contact us by sending a message using the form below:</p>
{{ HTML::ul($errors->all(), array('class'=>'errors'))}}
{{ Form::open(array('url' => 'contact')) }}
{{ Form::label('Subject') }}
{{ Form::text('subject','Enter your subject') }}
<br />
{{ Form::label('Message') }}
{{ Form::textarea('message','Enter your message') }}
<br />
{{ Form::submit() }}
{{ Form::close() }}
#stop
THe other pages works well
You need another route to display the contact form page
Route::get('contact', function() {
return View::make('contact');
});