How do I output a comma separated field as separate items efficiently? - meteor

I have a field in a mongodb collection with comma separated values such as...
{tags: 'Family friendly, Clean & tidy, Close to town centre, Good location, Friendly staff, Good breakfast, Book my next stay'}
In my template files I would normally call something like {{tags}}, or if I had an array might be able to use {{#each tags}} etc...
What I want to do though is wrap each item in additional HTML such as a span.
Any ideas?
UPDATE: Here's my helper function so far, it creates an array but I don't know the best way to use this in my HTML page so I can wrap spans around each item.
Template.tags.helpers({
getTags: function(input) {
var tagArray = [];
tagArray = input.split(',');
return tagArray;
}
})

You can use tags.split( ", " ), but storing the tags in an array is more flexible and makes more sense.

Using my helper getTags I could iterate over the array it returned with the following code:
{{#each getTags reviewTags}}
<span>{{this}}</span>
{{/each}}
The this keyword can be used to output each item.
I'm not sure if this is the most efficient way, but it keeps the HTML where I want it.

Related

VUEJS: Is it possible to process/modify data retrieved through v-for before displaying?

Hello I am extremely new to web application development / javascript in general. Only gave myself crash courses from udemy videos for the past 4 months.
For my web application, I am retrieving data from a database through my server-side backend with axios. I have a logRepository Array where the retrieved data is pushed.
data() {
return {
logRepository: [],
}
},
created() {
axios.get('/myrestapiroute', {
headers: {
'Authorization': `Bearer ${this.$store.state.token}`
},
params: {
userId: this.userId
}
})
.then(res => {
const data = res.data.logs
this.dataCheck = data
for(let key in data) {
const log = data[key]
log.id = key
this.logRepository.push(log)
}
})
On my template, I used v-for to loop through all the retrieved data elements:
<div ..... v-for="(log,index) in logRepository" :key="index">
With the v-for in place, one example of how I display my data as such in a paragraph tag. The format is due to how the data was structured.
<p style="text-align: justify;">
{{ log.logId.jobPerformed }}
</p>
The problem arises when I try to apply styling to the text. As you can see above, I would like to use text-align: justify. I also wanted to keep the whitespace as how it was input by the user through the use of white-space: pre-wrap.
(https://i.imgur.com/dwaJHT9.png)
But the problem is these two styles do not work together well. As can be seen below in the picture, if I use justify on its own, it behaves normally (Except that whitespace is lost). However, if I combine both text-align:justify and white-space: pre-wrap, the text end up justified with spacing, but aligned in a weird way.
(https://i.imgur.com/DQSfOya.png)
For short entries, they begin with weird indentation when the starting side should be aligned to the left of the column. The issue appears to be more than simply whitespaces at the start as I have tried .trim() as suggested by a contributor.
(https://i.imgur.com/uwysk9X.png)
I tried to tweak the CSS around, with text-align-last, text-align-start, direction: ltr, pre-tags etc. But it just does not work properly. Suggestions from other SO pages recommended that the data be processed by performing a string replace of all \n to br before displaying.
Is it possible to perform processing for individual data obtained from v-for before displaying or it has to be done to the array using computed property?
Since my data is to be fetched from a database, I am confused on how to achieve the pre-processing of data, since my array size will dynamic and differ for each user.
What would be the most optimal way to achieve pre-processing of data before displaying for such case?
This image below is how my Array of Object (logRepository) looks like. The format is largely due to mongoDB schema.
(https://i.imgur.com/7SilcF7.png)
======= Solution =======
I modified the object variables in my .then block and performed string replace for all \n characters to tags.
https://i.imgur.com/EtLX2tg.png
With that my display no longer requires the "white-space: pre-wrap" styling. However, since I was previously using string interpolation to display my data the tags were treated as plain text.
https://i.imgur.com/zUbNZbI.png
I had to modify the tags to use v-html binding to display the data as htmltext so that would work. The difference can be seen in the last picture.
https://i.imgur.com/sCTsCV4.png
Thanks for helping me on this since I am very new to javascript.
There are a number of patterns you could use here to pre-process your data.
Process your data in the then function you have created
Wrap the data in functions within the {{ ... }} blocks in the template
Create a component that is used as the element that the v-for loop iterates over which displays a computed value
Use a computed value as the source array of the v-for directive in the main template. This is often done using a processing function mapped to the source data, as in log.map( data => data.logId.jobPerformed.trim()

How can I scrape the string from this tag in ruby

I'm currently trying to do my first proper project outside of Codecademy/Baserails and could use some pointers. I'm using a scraper as part of one of the Baserails projects as a base to work from. My aim is to get the string "Palms Trax" and store it in array called DJ. I also wish to get the string "Solid Steel Radio Show" and store it in an array called source. My plan was to extract all the lines from the details section into a subarray and to then filter it into the DJ and Source arrays but if there is a better way of doing it please tell me. I've been trying various different combinations such as '.details none.li.div', 'ul details none.li.div.a' etc but can't seem to stumble on the right one. Also could someone please explain to me why the code
page.css('ol').each do |line|
subarray = line.text.strip.split(" - ")
end
only works if I declare the subarray earlier outside of the loop as in the Baserails project I am working from this did not seem to be the case.
Here is the relevant html:
<!-- Infos -->
<ul class="details none">
<li><span>Source</span><div> Solid Steel Radio Show</div></li>
<li><span>Date</span><div>2015.02.27</div></li>
<li><span>Artist</span><div>Palms Trax</div></li>
<li><span>Genres</span><div>Deep HouseExperimentalHouseMinimalTechno</div></li>
<li><span>Categories</span><div>Radio ShowsSolid Steel Radio Show</div></li>
<li><span>File Size</span><div> 135 MB</div></li>
<li><span>File Format</span><div> MP3 Stereo 44kHz 320Kbps</div></li>
</ul>
and my code so far:
require "open-uri"
require "nokogiri"
require "csv"
#store url to be scraped
url = "http://www.electronic-battle-weapons.com/mix/solid-steel-palms-trax/"
#parse the page
page = Nokogiri::HTML(open(url))
#initalize empty arrays
details = []
dj = []
source = []
artist = []
track = []
subarray =[]
#store data in arrays
page.css('ul details none.li.div').each do |line|
details = line.text.strip
end
puts details
page.css('ol').each do |line|
subarray = line.text.strip.split(" - ")
end
I'm Alex, one of the co-founders of BaseRails. Glad you're now starting to work on your own projects - that's the best way to start applying what you've learned. I thought I'd chip in and see if I can help out.
I'd try this:
page.css(ul.details.none li div a)
This will grab each of the <a> tags, and you'll be able to use .text to extract the text of the link (e.g. Solid Steel Radio Show, Palms Trax, etc). To understand the code above, remember that the . means "with a class called..." and a space means "that has the following nested inside".
So in English, "ul.details.none li div a" is translated to become "a <ul> tag with a class called "details" and another class called "none" that has an <li> tag nested inside, with a <div> tag nested inside that, with an <a> tag inside that. Try that out and see if you can then figure out how to filter the results into DJ, Source, etc.
Finally, I'm not sure why your subarray needs to be declared. It shouldn't need to be declared if that's the only context in which you're using it. FYI the reason why we don't need to declare it in the BaseRails course is because the .split function returns an array by default. It's unlike our name, price, and details arrays where we're using a different function (<<). The << function can be used in multiple contexts, so it's important that we make clear that we're using it to add elements to an array.
Hope that helps!

using the chrome console to select out data

I'm looking to pull out all of the companies from this page (https://angel.co/finder#AL_claimed=true&AL_LocationTag=1849&render_tags=1) in plain text. I saw someone use the Chrome Developer Tools console to do this and was wondering if anyone could point me in the right direction?
TLDR; How do I use Chrome console to select and pull out some data from a URL?
Note: since jQuery is available on this page, I'll just go ahead and use it.
First of all, we need to select elements that we want, e.g. names of the companies. These are being kept on the list with ID startups_content, inside elements with class items in a field with class name. Therefore, selector for these can look like this:
$('#startups_content .items .name a')
As a result, we will get bunch of HTMLElements. Since we want a plain text we need to extract it from these HTMLElements by doing:
.map(function(idx, item){ return $(item).text(); }).toArray()
Which gives us an array of company names. However, lets make a single plain text list out of it:
.join('\n')
Connecting all the steps above we get:
$('#startups_content .items .name a').map(function(idx, item){ return $(item).text(); }).toArray().join('\n');
which should be executed in the DevTools console.
If you need some other data, e.g. company URLs, just follow the same steps as described above doing appropriate changes.

XQuery -- Searching for full tags based on parts of a tag

I am having some issues when tackling a task in XQuery, FLWOR to be precise.
In one file, I deal with tags of full names, such as
<name>Neil Guyman</name>
but another xml file deals with
<firstname>Neil</firstname>
<secondname>Guyman</secondname>
Anyways, would this require any act of parsing?
Ideally there would be a parent element to these name elements that you can iterate over. If not, it's less pretty but you could just iterate over the first two and join the two elements for that case:
for $n in //(name | firstname)
return
typeswitch($n)
case element(name) return $n/string()
case element(firstname) return string-join(($n, $n/following-sibling::secondname),' ')
default **maybe throw an error?**

comma separated views list

everyone. I've got a problem with Views 2. I have a view with row's style set to fields (Got only title field). I want to display these titles with comma separated list.
For example:
Kazakhstan, England, China, Korea
tried to do this:
foreach($fields['title']->content as $titles) {
$zagolovki[] = $titles['view'];
}
$title_list = implode(', ', $zagolovki);
print $title_list;
but it doesn't works - says error in argument. Please help me someone to display node titles in views with comma separated list. Thanks!
I quikly took a look in the views-view-fields.tpl.php that comes with the views module and it says
/*
* - $view: The view in use.
* - $fields: an array of $field objects. Each one contains:
* - $field->content: The output of the field.
* - $field->raw: The raw data for the field, if it exists. This is NOT output safe.
* - $field->class: The safe class id to use.
* - $field->handler: The Views field handler object controlling this field. Do not use
* var_export to dump this object, as it can't handle the recursion.
* - $field->inline: Whether or not the field should be inline.
* - $field->inline_html: either div or span based on the above flag.
* - $field->separator: an optional separator that may appear before a field.
* - $row: The raw result object from the query, with all data it fetched.
*/
So I think $fields is what you should iterate over. If you want to debug the structure of your $fields install the devel-module and use dpm() or dsm() to display the content of $field. Maybe take the template you edited (that should be one of the view-module templates in the views/theme folder) and look what happens there.
Where does it say the error occurs, though? nonsenz is probably right that $fields['title']->content is not an array. For debugging only, try adding
print("array content: "+ is_array($fields['title']->content));
before the foreach. If you know that $fields is a small nested structure, you can try a
print(str_replace("\n","<br/>",print_r($fields,true));
to see what exactly is in it, so that you can make verify that what you're trying to iterate over is in fact iterable.
I've created this module:
http://drupal.org/project/views_delimited_list
I'm not too sure about fiddling with the options to create merely a comma-separated list. You should be able to, and if you can't I'll fix it.

Resources