berkeley-cdss / berkeley-class-site

A template for Berkeley CS and Data Science Classes
https://berkeley-cdss.github.io/berkeley-class-site/
MIT License
4 stars 4 forks source link

Create `CodeTag` plugin to render code files with and without solutions #29

Closed phrdang closed 2 weeks ago

phrdang commented 2 months ago

Created a custom Liquid tag called CodeTag as a Jekyll plugin. This tag allows staff to easily "import" code snippets located in the _includes/ directory, and hide/show solutions as needed.

Fixes https://github.com/phrdang/berkeley-class-site/issues/14

Next steps (in separate PRs)

phrdang commented 2 months ago

Maybe using the context variable will allow us to get jekyll variables/front matter? https://stackoverflow.com/questions/7919644/using-liquid-variables-inside-of-a-liquid-tag-call?lq=1

https://blog.sverrirs.com/2016/04/custom-jekyll-tags.html#accessing-post-variables-in-tags

https://github.com/Shopify/liquid/blob/main/lib/liquid/context.rb#L176

Will investigate...

edit: yep this works. example:

# frozen_string_literal: true

module Jekyll
  class MyTag < Liquid::Tag
    def render(context)
      context['page.nav_exclude'] == true # displays true when the tag is rendered if the variable is set to true
    end
  end
end

Liquid::Template.register_tag('my_tag', Jekyll::MyTag)
phrdang commented 1 month ago

Copying conversation from Slack:

@.cycomachead

Two comments: The name code is a little too generic? I don’t immediately have another name that’s short. example code_with_solutions assignment_code … maybe code is best since there’s no harm in using this for any code file, and it could syntax highlight, eventually. (oh we’ll need to use a custom theme for that!)

For the argument to show a solution ({% code questions/sample_question.py true %}) is there a way to use show_solution=true or maybe require that it be named? boolean args are kind of challenge to interpret. I am OK if that makes people write show_solution=page.show_solutions or something. If that’s a common enough use, maybe the plugin can read page variables, or even entire site variables…

@.phrdang

Yeah I wasn’t sure what the best name was. We could do include_code maybe? example and assignment_code might be too specific since you can theoretically include code for any reason (to show an example, to show problem starter code, to show the solution), etc.

I could definitely make it required to be named. Right now everything after the tag name is parsed as a string so we could just require show_solution= to be at the start