Skip to content

Instantly share code, notes, and snippets.

@ryanburnette
Last active December 17, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanburnette/5621254 to your computer and use it in GitHub Desktop.
Save ryanburnette/5621254 to your computer and use it in GitHub Desktop.
Sequence.py is a Python script I use to iterate over HTML elements creating a large block of sequential elements from a template. I use it mostly with Shopify were there aren't always methods for looping over repeated elements.
<div class="element" id="element-{{}}">
<span>Some stuff goes here. And it is sequential ... item #{{}}.</span>
</div>
<div class="element" id="element-1">
<span>Some stuff goes here. And it is sequential ... item #1.</span>
</div>
<div class="element" id="element-2">
<span>Some stuff goes here. And it is sequential ... item #2.</span>
</div>
<div class="element" id="element-3">
<span>Some stuff goes here. And it is sequential ... item #3.</span>
</div>
#! /usr/local/bin/python3
import sys
class Arguments:
def __init__(self):
self.argv = sys.argv
self.file()
self.iterations()
def file(self):
return self.argv[1]
def iterations(self):
try:
int(self.argv[2])
except:
print('Error: iterations')
sys.exit()
class Sequence:
def __init__(self, f, i):
try:
self.file = open(f)
self.html = self.file.read()
except:
print('Error: file')
sys.exit()
self.iterations = i
def do(self):
for x in range(1,self.iterations):
itTag = str(x)
newHtml = self.html.replace('{{}}', itTag)
print(newHtml)
def main():
arg = Arguments()
seq = Sequence(arg.argv[1], int(arg.argv[2])+1)
seq.do()
if __name__ == "__main__": main()
Here's how I use this. First, I'll create a template in a file in the directory with the script. Let's say I call that element-template.html. I use the placeholder `{{}}` in places where I want the sequence key to be placed.
Then I'll touch a file for the output and call it elements.html.
Then I put the script and output it to the elements.html file:
./sequence.py element-template.html 3 >> elements.html
And that gives me the result that I'll copy and paste into my Shopify theme or settings file.
---
Note that to use this yourself, you'll need to chmod 755 the file and set the #! line at the beginning of the file to the path of your own Python3 interpreter.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment