Shopify String Replace Array not working - arrays

I am new to shopify but upon my research... this code should work.
{% assign dcor = "decor, decors, Decor, Decors" | split: ", "%}
{% assign dcors = "décor, décors, Décor, Décors" | split: ", "%}
{{ product.title | replace: 'dcor', 'dcors' }}
But no luck at all.

Nope. Won't work. You can't match/replace elements from arrays. You have to manually replace each variation
{% assign dcor = "decor, decors, Decor, Decors" | split: ", "%}
{% assign dcors = "décor, décors, Décor, Décors" | split: ", "%}
{% assign d = dcor.size | minus: 1 %}
{% for i in (0..d) %}
{% assign title = product.title | replace: dcor[i],dcors[i] %}
{% endfor %}
{{ title }}

Related

If and else Statement in Boolean Field

my question seems tricky to me, but i'm certain someone could derive a solution to it. i've a boolean field, but i want to add a functionality in which when the boolean is been clicked (True), i could implement an {% if %} and {% else %} which could be, add a particular amount to the original amount, if the boolean field is True. my code is below for proper understanding...
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
paper = models.BooleanField(default=False, blank=True)
def get_final_price(self):
if self.item.discount_price:
return self.get_total_discount_price()
return self.get_total_item_price()
def coverframe(self):
return get_final_price() + 3000
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
item = models.ManyToManyField(OrderItem)
def __str__(self):
return self.user.username
def get_total_everything(self):
total = 0
for order_item in self.item.all():
total += order_item.get_final_price()
return total
def get_total_everything_cover_paper(self):
total = 0
for order_item in self.item.all():
total += order_item.coverframe()
return total
Views
class OrderSummary(LoginRequiredMixin, View):
def get(self, *args, **kwargs):
try:
******
context = {'object':order}
??????
except ObjectDoesNotExist:
messages.error(self.request, "No active order yet, sorry!!!")
return redirect('/')
and my html
{% if object.item.paper_frame %}
<tr>
<td><b>{{object.get_total_everything_cover_paper}}</b></td>
</tr>
<tr>
{% else %}
{% if object.get_total_everything %}
<tr>
<td><b>N {{object.get_total_everything}}</b></td>
</tr>
<tr>
{% endif %}
{% endif %}

How to check if some number is in_array in PhalconPHP volt?

I am looking for a in_array function equivalency in volt.
Is there another way to do this?
{% for modelObj in modelList %}
{% if modelObj.getId() in modelIdCheckedList %}
{{ check_field('id[]', 'value':modelObj.id, 'checked': true) }}
{% else %}
{{ check_field('id[]', 'value':modelObj.id, 'checked': null) }}
{% endif %}
{% endfor %}
I need to do something like this
{{ check_field('id[]', 'value':modelObj.id, 'checked': in_array(modelObj.getId(), modelIdCheckedList )) }}
Could you help me?
There are two ways you can achieve this.
Using a Function
Register the in_array as a function that Volt will understand. In your Volt registration you need to add the function to the compiler as follows:
$volt = new Phalcon\Mvc\View\Engine\Volt($view, $diContainer);
$volt->setOptions( .... );
$volt->getCompiler()->addFunction(
'in_array',
function ($parameters) {
return 'in_array(' . $parameters . ')';
}
);
Using an Extension
You can also register a PHP function extension, which will allow all PHP functions to work in Volt.
Create your extension class
class PhpFunctionExtension
{
/**
* This method is called on any attempt to compile a function call
*/
public function compileFunction($name, $arguments)
{
if (function_exists($name)) {
return $name . "(". $arguments . ")";
}
}
}
Register it in the Volt compiler
$volt = new Phalcon\Mvc\View\Engine\Volt($view, $diContainer);
$volt->setOptions( .... );
$volt->getCompiler()->addExtension(new PhpFunctionExtension());
https://docs.phalconphp.com/en/latest/reference/volt.html#extending-volt
https://docs.phalconphp.com/en/latest/reference/volt.html#extensions
Use the in operator:
{{ modelObj.getId() in modelIdCheckedList }}
So you may do something like:
{{ check_field('id[]', 'value': modelObj.id, 'checked': modelObj.getId() in modelIdCheckedList }}
Source: Volt - Other Operators

Django show only one element

I have product with image but when i try show image only this product django show me all image product how i can fix it ? I try wite slice don't work beacuse if i do |slice:"0:1" show me image but not image this product.
class Product(models.Model):
category = models.ForeignKey(Category, related_name='product')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='product/%Y/%m/%d',
blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
promo = models.BooleanField(default=False)
news = models.BooleanField(default=True)
section = models.CharField(max_length=50, choices=SECTION_CHOICES, default=None)
detailimage = models.ImageField(upload_to='product/detail/%Y/%m/%d',
blank=True)
detailimagetwo = models.ImageField(upload_to='product/detail/%Y/%m/%d',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
#property
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
#property
def detail_url(self):
if self.detailimage and hasattr(self.detailimage, 'url'):
return self.detailimage.url
#property
def detailtwo_url(self):
if self.detailimagetwo and hasattr(self.detailimagetwo, 'url'):
return self.detailimagetwo.url
def get_absolute_url(self):
return reverse('shop:product_detail',
args=[self.id, self.slug])
My views.py
def product_detail(request, id, slug):
product = get_object_or_404(Product,
id=id,
slug=slug,
available=True)
products = Product.objects.all()
return render(request,
'shop/product/detail.html',
{'product': product,
'products': products})
and my detail.html
{% extends "shop/base.html" %}
{% load static %}
{% block title %}{{ product.name }}{% endblock %}
{% block content %}
{% for p in products %}
<img src="{{p.detail_url}}" class="img-responsive">
{% endfor %}
</div>
</div>
{% endblock %}
if u want somethink more comment and i will how fast i can add it .
change your view
def product_detail(request, id, slug):
product = get_object_or_404(Product,
id=id,
slug=slug,
available=True)
return render(request,
'shop/product/detail.html',
{'product': product})
and in template change
{% for p in products %}
to
{% for p in product %}
you can solve the problem by removing one 's' in template but i suggest change the view function as mentioned
in case your using Pillow not just the address of image as string change this
{{p.detail_url}}
to
{{p.fieldname.url}}

Symfony array of arrays

Maybe there is a simpler way of doing this. But I want to display entries (URLs) that were already found when trying to input in to a database table along with the current table. So in the controller I am trying to pass two arrays. One that is of the whole table and another of the entries it found matched the entries in the table. So the user can see they already existed.
$repository = $this->getDoctrine()->getRepository('ObjectBundle:object');
foreach ($mylinks as &$value) {
$linkexist = $repository->findOneByUrl($value);
if (!$linkexist) {
$obj = new Object();
$obj->setUrl($value);
$obj->setLastupdate(new \DateTime('now'));
$em = $this->getDoctrine()->getManager();
$em->persist($obj);
$em->flush();
} else {
$notfound = new Object();
$notfound->setUrl($value);
}
}
$em = $this->getDoctrine()->getManager();
$listurls = $em->getRepository('ObjectBundle:Object')->findAll();
return $this->render('object/index.html.twig', array(
'objects' => $listurls,
));
I would like to include the $notfound into a separate array or parse it without changing the Object entity. Any ideas?
You Object contains some sort of Id and it can be used here:
$existingIds = array();
$k=0;
Then collect the IDs:
} else {
$notfound = new Object();
$notfound->setUrl($value);
$nfound[$k]=$notfound;
$k++;
}
Pass the array:
return $this->render('object/index.html.twig', array(
'objects' => $listurls,
'existingIds' => $existingIds
));
Finally, in your Twig, you would have something like this:
{% if existingIds is defined %}
{% for existingId in existingIds %}
{{ existingId.url }}
{% endfor %}
{% endif %}
Hope this helps a bit...

GAE ReferenceProperty Error from option value

I'm trying to add a new Goal via POST using my select option populated by the Referenced Category. The dropdown populates correctly, but the key I'm getting from the value returned is causing a ReferenceProperty Error.
models.py:
class Categories(db.Model):
name = db.StringProperty(required=True)
amount = db.FloatProperty(required=True)
class Goals(db.Model):
name = db.StringProperty(required=True)
amount = db.FloatProperty(required=True)
category = db.ReferenceProperty(Categories)
add_goal.html:
select type="select" name="category" id="id_cat"
{% for c in cats %}
option value='{{c.name}}' {{ c.name }} /option
{% endfor %}
/select>
CORRECTED VERSION:
{% for c in cats %}
{{ c.name }}
{% endfor %}
views.py:
def post(self):
cat_key = db.Key.from_path('Categories', self.request.get('category'))
logging.info('cat_key= '+ str(cat_key))
g = Goals(name=self.request.get('name'),
category=cat_key,
amount=float(self.request.get('amount')))
g.put()
return webapp2.redirect('/view_goals')
CORRECTED VERSION:
def post(self):
cat_key = db.Key.from_path('Categories', int(self.request.get('category')))
g = Goals(name=self.request.get('name'),
category=cat_key,
amount=float(self.request.get('amount')))
g.put()

Resources