The men tried to escape police after they were caught together.
Two Moroccan youths have been jailed for one and a half years and fined 2,000 dirhams (£375) each on charges of homosexuality.
The sentence was handed down by a court in the southern town of Tiznit on Monday (February 1).
The two men – identified in local media reports only as Hamza M and Osman A – were arrested by officers last week.
Although one the defendants – Hamza M – denied the charges throughout the trial, Osman A confessed that the pair were in a relationship and had slept with each other.
During their arrest, the men tried to escape by threatening the policemen with knives, however they soon apprehended.
Last month, two Moroccan men were arrested after a video of them kissing caused outrage online.
Moroccan law penalises acts of “sexual deviancy” between members of the same sex – a term that police reports and court documents use to refer to homosexuality more generally.
Gay sex is punishable by up to three years imprisonment and a fine.
Last year, campaigners condemned the jailing of two men accused of consensual same-sex activity in Morocco.
In May, three men in Morocco accused of homosexuality were jailed for three years each.
Ray Cole, a gay British man, was briefly jailed in the country in 2014 under Morocco’s anti-gay laws.
Mr Cole and his Moroccan friend were subsequently released following a high-profile campaign.