Automatically add divs to product descriptions in Shopify - javascript

I'm trying to add divs to product descriptions in Shopify so that I can then create an accordion.
Currently my code looks like this
In the .liquid file:
<div class="product-single__description rte">
{{ product.description }}
</div>
This is the output:
<div class="product-single__description rte">
<h2>TEXT</h2>
<h4>TEXT</h4>
<p><em>Text</em></p>
<h4>TEXT</h4>
<p>Text</p>
<h2>TEXT</h2>
<h4>Text</h4>
<p>Text</p>
<h4>TEXT</h4>
<p>Text</p>
<h4>TEXT</h4>
<p>Text</p>
<p><em>Text</em></p>
</div>
My goal is to insert a div wrapper and enclose the content from H2 to the next h2, so for example:
<div class="product-single__description rte">
<div class=“class_1”
<h2>TEXT</h2>
<h4>TEXT</h4>
<p ><em>Text</em></p>
<h4>TEXT</h4>
<p>Text</p>
</div>
<div class=“class_2”
<h2>TEXT</h2>
<h4>Text</h4>
<p>Text</p>
<h4>TEXT</h4>
<p >Text</p>
<h4>TEXT</h4>
<p>Text</p>
<p><em>Text</em></p>
</div>
</div>
The number of H2s and the content changes from product to product.

Well there are a few checks that you need to make before you do this.
First we will set a variable for the content:
{% assign content = product.description %}
After that we will check if the if there is a plain <h2> in there
{% if content contains '<h2>' %}
// logic to add here
{% else %}
{{content}}
{% endif %}
(have in mind that if your h2 tags have any inline styles you will have to target <h2 instead)
If there is we will continue the logic inside the if, but if there is not we will output the plain content in the else statement.
So we are now in the // logic to add here part here.
We will split the content by <h2> like so:
{% assign content_arr = content | split: '<h2>' %}
We will check if you have some content before the first <h2> since we don't want to loose it in that case, so we check it like so:
{% if content_arr[0] != '' %}
{{content_arr[0]}}
{% endif %}
We need to loop the rest of the items of the array.
Since we are splitting by <h2> if there is no content before the <h2> it will return an empty array for the first item and we don't need that one. So we will offset the for loop by 1 item:
{% for item in content_arr offset: 1 %}
// items here
{% endfor %}
Now we need to return the opening <h2> tag (since we removed it from the content) and show the rest of the content.
It's easy as writing <h2> before the {{item}}:
<div class="class_{{forloop.index}}">
<h2>{{item}}
</div>
And that's all.
Here is the full code:
{% assign content = product.description %}
{% if content contains '<h2>' %}
{% assign content_arr = content | split: '<h2>' %}
{% if content_arr[0] != '' %}
{{content_arr[0]}}
{% endif %}
{% for item in content_arr offset: 1 %}
<div class="class_{{forloop.index}}">
<h2>{{item}}
</div>
{% endfor %}
{% else %}
{{content}}
{% endif %}

You may try this (not tested but it should work):
{% assign desc_parts = product.description | split:'<h2>' %}
{% for part in desc_parts offset:1 %}
<div class="class_{{ forloop.index }}">
{{ part | prepend:'<h2>' }}
</div>
{% endfor %}
Explanations:
As you do not have clean separator in product description, let's use
h2 tag.
Then, you create an array with this separator (split
function).
Then you loop through your array, with an offset to 1 to
avoid the empty first elem (or you may use it later or before to display it in a separated div it there is something before the first h2 tag). To display separately the first elem, use {{ desc_parts.first }}.
To get a unique class or id, you may
use the loop index.
As the h2 tag is the separator used to create
the array, you need to prepend your elem with it.
Please note that you should also think about the case with a product description without h2 and manage this case in your code.

Related

(JS) Markdown issue in flask

I have a small problem with markdown in my flash project.
I want markdown to work for all posts, currently it only works for the first post. I suspect I need to use some kind of loop, but I don't know what to do to make it work.
Code:
{% extends "layout.html" %}
{% block content %}
<article class="media content-section">
<div class="media-body">
{% for post in document.posts %}
<div class="article-metadata">
<h3><a class="article-title" href="{{ url_for('posts.post', post_id=post.id) }}">{{ post.title }}</a></h3>
<p class="article-content">{{ post.content }}</p>
</div>
{% endfor %}
</div>
</article>
<script>
const content_text = document.querySelector(".article-content");
content_text.innerHTML = marked(content_text.innerHTML);
</script>
{% endblock content %}
Pic of the posts on website
querySelector returns the first element with the class. You need to use querySelectorAll to get all the elements and then use for loop to loop and apply markdown to each element.
const content_text = document.querySelectorAll(".article-content");
for (i = 0; i < content_text.length; i++){
content_text[i].innerHTML = marked(content_text[i].innerHTML);
}

Show and hide text of different posts

I have several posts each of them composed of three parts : a title, a username/date and a body. What I want to do is to show the body when I click on either the title or the username/date and hide it if I click on it again. What I've done so far works but not as expected because when I have two or more posts, it only shows the body of the last post even if I click on another post than the last one. So my goal is only to show the hidden text body corresponding to the post I'm clicking on. Here is my code:
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}Test page{% endblock %}</h1>
<a class="action" href="{{ url_for('main_page.create') }}">New</a>
{% endblock %}
{% block content %}
{% for post in posts %}
<article class="post">
<header>
<script language="JavaScript">
function showhide(newpost)
{var div = document.getElementById(newpost);
if (div.style.display !== "block")
{div.style.display = "block";}
else {div.style.display = "none";}}
</script>
<div onclick="showhide('newpost')">
<h1>{{ post['title'] }}</h1>
<div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%d-%m-%Y') }}</div>
</div>
</header>
<div id="newpost">
<p class="body">{{ post['body'] }}</p>
</div>
</article>
{% if not loop.last %}
<hr>
{% endif %}
{% endfor %}
{% endblock %}
Of course I looked for a solution as much as I could but I'm kind of stuck plus I'm a complete beginner in HTML/JS/CSS. And one last thing, I'm currently using Python's framework Flask. Thank you by advance.
You need to give each of your posts a unique id for your approach to work.
Change your code to
<div id="{{post_id}}">
<p class="body">{{ post['body'] }}</p
</div>
where post_id is that post's unique id e.g. its id in the database you are using that you pass to the template in your view. Then, change the call to the onclick event handler to
<div onclick="showhide('{{post_id}}')">
If you don't have a unique id you can also use the for loop's index: replace all post_id instances above with loop.index. See Jinja's for loop docs for more information.

Create an iterative counter in DJango template

I've checked a lot of other questions and I haven't seen my particular scenario really addressed and I've tried a lot of things out without success.
What I have is a DJango for loop in my HTML code, and within the for loop is an if statement checking if each element from the list that is being looped through equals a certain value. If that is true, then an entry is created on the page. I need to dynamically print the element number (eg. entry 1 would display as 1. and entry 2 would display as 2.)
The two best attempts I have made are:
1.
<!-- this approach prints out 1 for each entry -->
{% with counter=0 %}
{% for q in questionnaire.questions %}
{% if q.answer %}
<div class="row"><h3>
{{ counter|add:1 }}. {{ q.name }}
</h3></div>
<!-- some other code-->
{% endif %}
{% endfor %}
{% endwith %}
{% for q in questionnaire.questions %}
{% if q.answer %}
<div class="row"><h3>
<span id="displayCount">0</span>. {{ q.name }}
</h3></div>
<!-- some other code-->
{% endif %}
{% endfor %}
<script type="text/javascript">
var count = 0;
var display = document.getElementById("displayCount");
count++;
display.innerHTML = count;
</script>
Any help would be appreciated
You can access the built-in counter of your for loop using forloop.counter. It starts at 1, you can also you forloop.counter0 if you'd like to start at zero.
{% for q in questionnaire.questions %}
{% if q.answer %}
<div class="row">
<h3>
{{ forloop.counter }}. {{ q.name }}
</h3>
</div>
<!-- some other code-->
{% endif %}
{% endfor %}
Filter your queryset in your view as to avoid issues with indexing and separating presentation from logic.

OctoberCMS Javascript API AJAX call to a component function to update component's partial

So I have the following file structure:
plugins/myname/pluginname/components/pluginname/default.htm
plugins/myname/pluginname/components/PluginName.php
default.htm acts as the partial of the component.
and I have the following JS API
setInterval(function(){
$.request('onEverySecond', {
update: {'#default.htm':'#rate-marquee'},
complete: function() {
console.log('Finished!');
}
})
}, 1000);
onEverySecond is a function in PluginName.php that updates a variable called fx thrown to default.htm.
At the front end the partial default.htm seems to be updated, but it refreshes the whole partial which is not what I want, it causes the marquee to replay again and again and only be able to show the first few piece of contents.
All I wanted is that the AJAX will update only the variable fx where the data is updated.
How can I achieve that?
EDIT 1:
Here is the partial markup:
{% set fx = __SELF__.fx %}
<marquee id="rate-marquee" name="rate-marquee" onmouseover="this.stop();" onmouseout="this.start();">
<ul>
{% for item in fx %}
<li>
{{ item.Item | trim('u')}}: {{ item.BID }} {% if item.Revalue == 0 %} <div class="arrow-up"></div> {% else %} <div class="arrow-down"></div> {% endif %}
</li>
{% endfor %}
</ul>
</marquee>
Additionally, here is the code in PluginName.php
public function onRun()
{
$this->addJs('/plugins/SoyeggWebDevelopment/fxmarquee/assets/js/default.js');
$this->updateFX();
}
public function onEverySecond()
{
$this->updateFX();
}
public $fx;
So updateFX() works perfectly well too.
Here problem seems you are replacing whole marquee it causes to re-render it.
To solve this we can just update portion inside marquee
setInterval(function(){
$.request('onEverySecond', {
complete: function() {
console.log('Finished!');
}
})
}, 1000);
We don't do anything special here just a simple ajax call
to update portion of marquee we need to assign id to it and we define internal partial
<marquee id="rate-marquee"
name="rate-marquee"
onmouseover="this.stop();" onmouseout="this.start();">
<ul id='rate-marquee-inner'> <!-- <= here -->
{% partial __SELF__ ~ '::_marquee_inner' %}
</ul>
</marquee>
_marquee_inner.htm partila markup
{% set fx = __SELF__.fx %}
{% for item in fx %}
<li>
{{ item.Item | trim('u')}}: {{ item.BID }} {% if item.Revalue == 0 %} <div class="arrow-up"></div> {% else %} <div class="arrow-down"></div> {% endif %}
</li>
{% endfor %}
and to update that portion we just need to return markup array
function onEverySecond() {
$this->updateFX();
return ['#rate-marquee-inner' => $this->renderPartial('_marquee_inner.htm')];
}
this will just push new updated markup to given id #rate-marquee-inner so now it will just update inner portion of marquee and marquee will not re-render.
if any doubt please comment.

putting jekyll tags in an "onclick" breaks

in jekyll, this works:
---
layout: default
---
<div class="brief">
<ul>
{% for post in site.posts %}
<li class="postlist">
<a href="#" onclick='document.getElementById("one").innerHTML="{{post.url}}";'>{{post.title}}</a>
<p>{{post.meta}} <br>{{post.date}} <br>{{post.category}}</p>
</li>
{% endfor %}
</ul>
</div>
<div class="post" id="one"></div>
but when i change line #8 to:
<a href="#" onclick='document.getElementById("one").innerHTML="{{post.content}}";'>{{post.title}}</a>
it breaks. why does this happen and what can i do to change this and get the desired outcome?
It's likely that your post content is creating invalid HTML (e.g. ending the onclick quotes).
In my opinion, a better method to achieve this would be to render all the post content hidden, and have your onclick toggle a class to display the relevant content. This would save you from the untold horrors of encoding and decoding that content through an attribute value.
For example:
{% for post in site.posts %}
<li>
<a href="#" onclick='document.getElementById("post-content-{{ forloop.index }}").classList.toggle("hidden")'>{{ post.title }}</a>
<p>{{ post.meta }} <br>{{ post.date }} <br>{{ post.category }}</p>
<p id="post-content-{{ forloop.index }}" class="hidden">{{ post.content }}</p>
</li>
{% endfor %}
External CSS:
.hidden {
display: none;
}
You could also extend this to hide all content sections first, so only one is shown at a time.

Categories

Resources