2

In teaching myself Flask, I have fallen into the habit of doing something like this in some of my templates:

<script type="text/javascript">
{% for r in reviews %}
    $('#{{ r.review_id }}-starrating').raty({readOnly: true, score: {{ r.rating/100 * 5 }} });
{% endfor %}
</script>

I didn't think twice about it when I first needed something like this done. But coming back to this code now worries me. Is this considered bad practice? How should I do this instead?

1 Answer 1

1

It's a good question which shows you've gaining some intuition for what is good/bad programming. There is nothing wrong with doing what you describe: I mean it will work, and work well for some people.

But, in my experience, whilst it's easy for trivial stuff, once the application gets long and busy things get tricky to maintain. I think the programming principle violated is called something like maintaining a separation of concerns. The problem is you are writing code which must respect two scopes at once: the server and the client; it's always easier to focus on one at a time.

One way to quickly simplify the problem is to write a pure javascript routine which is then called with server generated data.

That might go something like:

// a pure js function
function render_rating(elid, rating){
      $elid.raty({readOnly: true, score: rating/100 * 5})
}

And list all the invocations neatly someplace else:

<script type="text/javascript">
// server generates a list of function calls which render the ratings client side
{% for review in reviews %}
   render_rating('#{{review.id}}-starrating', {{review.rating}});
{% endfor %}
</script>

The idea is to separate the code into two distinct fragments so it is clear "this is stuff that happens on the client", and "this is stuff that happens on the server".

When the javascript routines get long and complex (like ajax applications) this kind of thinking makes it much easier to create static (cachable) javascripts which can be called by serverside generated data embedded into html and, as things get even more advanced, invoked by other js routines which are acting on data returned by ajax api calls.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.