Skip to content

Cards not created properly when the model template contains {{^FieldName}} #151

@twtu

Description

@twtu

Description
Cards with conditional replacements of the form {{^FieldName}} are not handled correctly.
I think I have tracked it to an error in the line
rendered = chevron.render(template['qfmt'], field_values)
in model.py
that is, it does no render the same as anki.

Note that if you import the apkg generated by genanki into anki and then run "Check Database" anki will then create the correct cards.

To reproduce, add the following to test_genanki.py

TEST_MODEL_MUST_HAVE_HINT = genanki.Model(
  456789, 'with hint',
  fields=[{'name': 'Question'}, {'name': 'Hint'}, {'name': 'Answer'}],
  templates=[
    {
      'name': 'card1',
      'qfmt': '{{#Hint}}{{Question}}<br>Hint: {{Hint}}{{/Hint}}',
      'afmt': '{{Answer}}',
    },
  ],
)

TEST_MODEL_MUST_NOT_HAVE_HINT = genanki.Model(
  456789, 'with hint',
  fields=[{'name': 'Question'}, {'name': 'Hint'}, {'name': 'Answer'}],
  templates=[
    {
      'name': 'card1',
      'qfmt': '{{^Hint}}{{Question}}<br>Hint: {{Hint}}{{/Hint}}',
      'afmt': '{{Answer}}',
    },
  ],
)


  def test_notes_generate_cards_based_on_req__must_have_hint(self):
    # only n2 has a hint and will generate one card
    n1 = genanki.Note(model=TEST_MODEL_MUST_HAVE_HINT, fields=['capital of California', '', 'Sacramento'])
    n2 = genanki.Note(model=TEST_MODEL_MUST_HAVE_HINT, fields=['capital of Iowa', 'French for "The Moines"', 'Des Moines'])

    assert len(n1.cards) == 0
    assert len(n2.cards) == 1
    assert n2.cards[0].ord == 0

  def test_notes_generate_cards_based_on_req__must_not_have_hint(self):
    # n2 has a hint so only n1 will generate one card
    n1 = genanki.Note(model=TEST_MODEL_MUST_NOT_HAVE_HINT, fields=['capital of California', '', 'Sacramento'])
    n2 = genanki.Note(model=TEST_MODEL_MUST_NOT_HAVE_HINT, fields=['capital of Iowa', 'French for "The Moines"', 'Des Moines'])

    assert len(n1.cards) == 1
    assert n2.cards[0].ord == 1
    assert len(n2.cards) == 0
    # The following commented lines make the test pass, but they are wrong.
    # assert len(n1.cards) == 1
    # assert len(n2.cards) == 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions