For example, in PHP a way to parse RSS feed could be:
<?php
$rss = simplexml_load_file('http://blog.wordpress_site.com/feed/');
{{ rss }}
foreach ($rss->channel->item as $item) {
echo $item->title;
echo $item->link;
echo $item->description;
echo $item->guid;
}
?>
How can I have this on Twig?
UPDATE: Thanks to the reply I got it. Now it gets this by item but not some fields like image, category or text of the post:
SimpleXMLElement {#955 ▼
+"title": "Website. Description of the website"
+"link": "http://blog.website.com/liktothepost"
+"pubDate": "Fri, 17 Feb 2017 07:56:43 +0000"
+"category": SimpleXMLElement {#1131}
+"guid": "http://blog.website.com/?p=400"
+"description": SimpleXMLElement {#953}
}
You would create a controller with an action to pass the object to your Twig file that you want to render like so:
public function viewRSSAction(Request $request){
$rss = simplexml_load_file('http://blog.wordpress_site.com/feed/');
return $this->render('my_rss.html.twig', array(
'rss' => $rss,
));
}
Then your my_rss.html.twig might look like this:
{% for item in rss %}
{{ item.title }}
{{ item.link }}
{{ item.description }}
{{ item.guid }}
{% endfor %}
Related
I have a problem with properties in (probably) Twig. I have controller in Symfony where getCategories(), getWords(), getTranslations() methods (from Doctrine) return the objects (relations). Every property in the controller is an array because I call findAll() method (from Doctrine again) which returns the array. Finally I return all the properties from controller to view (Twig file) where I try display the results by Twig for loop.
The problem is the Twig loop only iterates over flashcards property (I know why ;)) and I have no idea how to make many-properties iterating. I'd like the loop to iterate over all properties returned by the controller.
In the controller foreach loop I tried update the flashcards array with new associative keys such as: category, word and translation so that all the results returned by Doctrine (including relations) are stored in one flashcards property but then Symfony throws exceptions.
I wondered if create one array in the controller to which I would push the flashcards, cateogry, word and translation arrays and then return this one array to the view but I don't think this is good practice.
Here's the controller method code:
public function showAllCards()
{
$flashcards = $this->getDoctrine()->getRepository(Flashcards::class)
->findAll();
foreach ($flashcards as $flashcard) {
$category = $flashcard->getCategories()->getName();
$word = $flashcard->getWords()->getWord();
$translation = $flashcard->getTranslations()->getWord();
}
return $this->render('try_me/index.html.twig', [
'flashcards' => $flashcards,
'category' => $category,
'word' => $word,
'translation' => $translation
]);
}
Here's the Twig loop code:
{% for flashcard in flashcards %}
{{ word }}
<br>
{{ flashcard.pronunciation }}
<br>
{{ flashcard.exampleSentence }}
<br>
{{ category }}
<br>
{{ translation }}
<br>
{% endfor %}
I tried to execute the following controller code...
public function showMeAll()
{
$flashcards = $this->getDoctrine()->getRepository(Flashcards::class)
->findAll();
foreach ($flashcards as $flashcard) {
$flashcards['categories'] = $flashcard->getCategories()->getName();
$flashcards['words'] = $flashcard->getWords()->getWord();
$flashcards['translations'] = $flashcard->getTranslations()->getWord();
}
return $this->render('try_me/index.html.twig', [
'flashcards' => $flashcards,
]);
}
...with the following Twig loop...
{% for flashcard in flashcards %}
{{ flashcard.words }}
<br>
{{ flashcard.pronunciation }}
<br>
{{ flashcard.exampleSentence }}
<br>
{{ flashcard.categories }}
<br>
{{ flashcard.translations }}
<br>
{% endfor %}
...but then Symfony says:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Proxies__CG__\App\Entity\Words could not be converted to string").
Could you give me some tips how to solve this problem, please? I'd like the Twig loop to iterates over many properties (flashcard, word, category, translation). Or write if there's a better solution, please.
Thank you in advance for every answer!
According to your snippets, I'm guessing you want something like the following:
{% for flashcard in flashcards %}
{% for word in flashcard.getWords() %}
{{ word }}<br />
{% endfor %}
{{ flashcard.getPronunciation() }}<br>
{{ flashcard.getExampleSentence() }}<br>
{% for category in flashcard.getCategories()() %}
{{ category.getName() }}<br />
{% endfor %}
{% for translation in flashcard.getTranslations() %}
{{ translation.getWord() }}<br />
{% endfor %}
{% endfor %}
Have a look at this section of the documentation. Basically if you had foo.bar, twig will test if bar is a public property of foo and if not test if there is a public getter, getBar, to fetch bar.
Some sidenotes in both of your loops, the values category, word and translation will only hold the last value of your flashcards, because you are overwriting the value each time.
I have been trying to figure out how I can pull the url of a node content type using an entity reference.
Apparently using {{ links.entity.uri }} or {{ links.entity.url }} does not work
<div>
{% for links in node.field_related_items %}
<h2>{{ links.entity.label }}</h2>
<a href="{{ links.entity.uri }} " ></a>
{% endfor %}
</div>
This worked for me:
This will only take you to /node/entity_id though and not /entity_name/entity_id
I would like to expand upon this answer by saying that you should add a Drupal::entityQuery() to your .theme file. Inside of this query, you'll want to grab the "alias" which is the link to the content. In your case this will give you these links /migrations and /aboutiom.
Here's an example of what that might look like...
function theme_name_preprocess_node(&$variables) {
$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('type', 'related_links')
$nids = $query->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
$related_links = [];
foreach ($nodes as $item) {
$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$item->id());
$related_links[] = [
'title' => $item->getTitle(),
'id' => $item->id(),
'field' => $item->get('field_name')->value,
'alias' => $alias,
];
}
$variables['related_links'] = $related_links;
}
Now in your twig template you can do something like this...
{% for link in related_links %}
{{ link['title'] }}
{% endfor %}
I got the following from controller :
{"cat_id":17,"course":"Maths",
"subcat_info":[{"subcat_id":43,"title":"Test","cat_id":17}]}
Now I want to fetch the title of (title:test) from subcat_info.
I tried following foreach in blade view (result is blank)
#foreach($cats as $cat)
{{ $cat->subcat_info[0]->title }}
#end
How to get title from this?
Try this
$json = '{
"cat_id":17,
"course":"Maths",
"subcat_info":[{
"subcat_id":43,
"title":"Test",
"cat_id":17
}]
}';
$array = json_decode($json,true);
echo $array['subcat_info'][0]['title'];
Output
Test
#foreach($cats as $cat)
{{ $cat->course }} // if you like to print the "title" of the category
#foreach($cat->subcat_info as $subcat)
{{ $subcat->title }}
#endforeach
#endforeach
I have file "header.html" in partial folder, here my code
<ul class="sf-menu" id="mainMenu">
{{ shoesmart:showMenu group="header" indent="tab"}}
<li>{{ name }}
{{ if children }}
<ul>
{{ children }}
<li>{{ name }}</li>
{{ /children }}
</ul>
{{ endif }}
</li>
{{/shoesmart:showMenu}}
</ul>
and I have file "shoesmart.php" in plugins folder, here my code :
function showMenu()
{
$return = '';
$menu_list = $this->db->select('*,CONCAT(pua.type,"/",pua.keyword) as path',false)
->from('menu mn')
->join('product_url_alias pua','mn.url_alias_id=pua.url_alias_id','LEFT')
->where('status',1)
->get()
->result_array();
foreach ($menu_list as $result) {
$return[] = array(
'name' => $result['name'],
'url' => BASE_URL.'home/'.$result['path']
);
}
return $return;
}
and my table name in database is "default_menu" that have structure:
menu_id url_alias_id name status parent_id
1 868 Men 1 0
2 869 woman 1 0
but when I refresh in browser, just show main menu, its mean that the submenu didn't show. Should I change my code ? or I also add new table for submenu in my database ?So please help me .. I have deadline project tomorrow T.T
This is probably relatively easy to do, but I'm new to twig and I'm frustrated.
I'm adapting code from this answer: https://stackoverflow.com/a/24058447
the array is made in PHP through this format:
$link[] = array(
'link' => 'http://example.org',
'title' => 'Link Title',
'display' => 'Text to display',
);
Then through twig, I add html to it, before imploding:
<ul class="conr">
<li><span>{{ lang_common['Topic searches'] }}
{% set info = [] %}
{% for status in status_info %}
{% set info = info|merge(['{{ status[\'display\'] }}']) %}
{% endfor %}
{{ [info]|join(' | ') }}
</ul>
But I'm getting:
Errno [8] Array to string conversion in
F:\localhost\www\twig\include\lib\Twig\Extension\Core.php on line 832
It's fixed when I remove this line, but does not display:
{{ [info]|join(' | ') }}
Any ideas how I can implode this properly?
** update **
Using Twig's dump function it returns nothing. It seems it's not even loading it into the array in the first place. How can I load info into a new array.
info is an array, so you should simple write
{{ info|join(', ') }}
to display your info array.
[info] is a array with one value : the array info.
You shouldn't really be building complex data structures inside of Twig templates. You can achieve the desired result in a more idiomatic and readable way like this:
{% for status in status_info %}
{{ status.display }}
{% if not loop.last %}|{% endif %}
{% endfor %}
You can user json_encode for serialize array as strig, then show pretty - build in twig
{{ array|json_encode(constant('JSON_PRETTY_PRINT')) }}
if need associative array:
{{info|json_encode(constant('JSON_PRETTY_PRINT'))|raw}}